0

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"}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
RAD
  • 1
  • 1
    This isn't a question about how to *deserialize* something, it's about how to *flatten* a JS object. Just FYI. I'll try to answer below. – BishopRook Aug 24 '11 at 19:55

2 Answers2

1

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?

Community
  • 1
  • 1
acanimal
  • 4,800
  • 3
  • 32
  • 41
1

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?

BishopRook
  • 1,240
  • 6
  • 11