Search code examples
javajavascriptjsongsonstringify

How to obtain the same result with google-Gson and JSON.stringfy


in my java code, I have a class with o member of type Map<String,String>. I use google Gson library to convert from object to json string and viceversa.

I want to do the same with javascript and the JSON library from json.org.

The problem is javascript hasn't "map objects" and if I use arrays to emulate maps, the results of JSON.stringify over arrays is not the same as Gson over Map<String,String>.

I also tried with Hashtable javascript object from the library jshashtable 2.1 (http://www.timdown.co.uk/jshashtable/index.html) and creating a custom toJSON method but this approach didn't work because what JSON does in these cases is stringify the object returned by the custom toJSON method.

This is what I get:

With java and Gson:

{
    "var_1": "value_1",
    "var_2": "value_2",
    "map": {
        "name_1": "value_1",
        "name_2": "value_2"
    }
}

With javascript and JSON:

{
    "var_1": "value_1",
    "var_2": "value_2",
    "map": [
        ["name_1", "value_1"],
        ["name_2", "value_2"]
    ]
}

Is there any way to resolve this and obtain the same "json strings" from java and javascript?

Thanks in advance...


Solution

  • The problem is javascript hasn't "map objects"...

    Yes, it does: All JavaScript objects are maps. To get what you're looking for, you'd create this object graph:

    var obj = {
        "var_1": "value_1",
        "var_2": "value_2",
        "map": {
            "name_1": "value_1",
            "name_2": "value_2"
        }
    };
    

    ...and use JSON.stringify on it.

    var json = JSON.stringify(obj);
    

    That bit after var obj = looks familiar? That's because it's a JavaScript object initializer, and JSON is a subset of object initializer syntax. :-) You could build that object in other ways if you like:

    var obj = {};
    obj.var_1 = "value_1";
    obj.var_2 = "value_2";
    obj.map = {};
    obj.map.name_1 = "value_1";
    obj.map.name_2 = "value_2";
    

    ...which would also give you the same thing after calling JSON.stringify on it.