Reputation: 1
I converted a Java object that had string and linked hashmap into JSON using GSON.toJson. The output from this process is a combination of key:value pairs and an array as below:
{"a":"b", "c":"d", "featuremap":{"e":"f", "g":"h"}}
Could you please advise on how I can deserialize this into a string that contains key:value pairs ONLY i.e. the featuremap array is resolved so that the output is:
{"a":"b", "c":"d", "e":"f", "g":"h"}
Upvotes: 0
Views: 417
Reputation: 1260
It depends: is it always going to be an object like
var objToFlatten = {
"a": "b",
"c": "d",
"featuremap": {
"e": "f",
"g": "h"
}
}
Or could it potentially be multi-nested, with multiple objects to flatten? For example:
var objToFlatten = {
"a": "b",
"c": "d",
"featuremap": {
"e": "f",
"g": "h"
},
"someothermap": {
"e": "f",
"g": "h",
"nestedmap": {
"i": "j"
}
}
}
The first is easy-ish but hacky.
function copyFromObject(other) {
for (var propertyName in other) {
if (propertyName == 'featureMap') continue;
if (other.hasOwnProperty(propertyName)) {
this[propertyName] = other[propertyName];
}
}
return this;
}
var flattened = copyFromObject.call({}, objToFlatten);
The latter would be cleaner and would require a recursive solution. Also you'd need to figure out what you want to do about things like duplicated entries. What if you have two properties in two nested objects with the same name?
Upvotes: 1
Reputation: 5020
Take a look to GSON doc. You can write your own serializer/deserializer for a specific type
https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer
How do I write a custom JSON deserializer for Gson?
Upvotes: 1