Search code examples
javajsonhashmapgson

Parsing JSON object into a Map using Gson - JsonSyntaxException


I have a map property:

private Map<String, Attribute> attributes = new HashMap<>();

Attribute object looks like this:

public class Attribute{
     private String value;
     private String name;

//with constructor setters and getters
}

How do I represent attributes Map object as JSON?

I am getting a JsonSyntaxException:

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

when I'm trying to convert JSON object using fromJson() in the following code:

Attribute attribute = Gson().fromJson(jsonObect,Attribute.class)

My JSON object looks like this:

{
   "attributes":[
      {
         "name":"some name",
         "value":"some value"
      }
   ]
}

Solution

  • it is easy to check:

        Map<String,Attribute> attributes = new HashMap<>();
        attributes.put("key_0", new Attribute("value_0", "name_0"));// I added constructor and getter/setter methods to class Attribute
        attributes.put("key_1", new Attribute("value_1", "name_1"));
        attributes.put("key_2", new Attribute("value_2", "name_2"));
        //serialize using ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        var s = mapper.writeValueAsString(attributes);
        System.out.println(s);
    

    output:

    {
       "key_2":{
          "value":"value_2",
          "name":"name_2"
       },
       "key_1":{
          "value":"value_1",
          "name":"name_1"
       },
       "key_0":{
          "value":"value_0",
          "name":"name_0"
       }
    }