harish
harish

Reputation: 2493

Convert complex Java object to Json using Gson

I am using GSON to serialize Java object.

I have a Java class with following properties.

String property1;
Map<String, HashMap> property2 = new HashMap<>();
Map<String, ArrayList<String>> property3 = new HashMap<>();
Map<String, String[]> property4 = new HashMap<>();

I want to convert this to Json. Because of the maps with HashMaps inside, it has become difficult. I know I can get Json of a map with gsonObject.toJson(map). But I want all these properties in the Json Object. (all in one. not Concatenating many objects)

Can anyone help me to get this done?

Upvotes: 0

Views: 1917

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

I don't see what the problem is. Gson can serialize Maps just fine.

Assuming your class is named Test

Test test = new Test();

test.property1 = "some value";

HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("fourty two", 42);
test.property2.put("property2-key", map);

ArrayList<String> strings = new ArrayList<>(Arrays.asList("string1",
            "string2", "string3"));
test.property3.put("property3-key", strings);

String[] stringArray = { "array1", "array2", "array3" };
test.property4.put("property4-key", stringArray);

Gson gson = new Gson();
String json = gson.toJson(test);
System.out.println(json);

It generates the following

{
    "property1": "some value",
    "property2": {
        "property2-key": {
            "fourty two": 42,
            "one": 1
        }
    },
    "property3": {
        "property3-key": [
            "string1",
            "string2",
            "string3"
        ]
    },
    "property4": {
        "property4-key": [
            "array1",
            "array2",
            "array3"
        ]
    }
}

Upvotes: 1

Related Questions