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"
}
]
}
CodePudding user response:
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"
}
}
CodePudding user response:
I am getting:
"Expected BEGIN_ARRAY but was BEGIN_OBJECT"
error when I'm trying to convert JSON object usingfromJson()
in the following code:
Attribute attribute = Gson().fromJson(jsonObect,Attribute.class)
The following JSON object doesn't match either a single Attribute
object or a map Map<String, Attribute>
:
{
"attributes":[
{
"name":"some name",
"value":"some value"
}
]
}
Have a look carefully, the value mapped to the key "attributes"
is a JSON-array.
Hence, you can parse it successfully into a map of type Map<String, List<Attribute>>
That's how it can be implemented using Gson.fromJson()
and TypeToken
(for more options, see this question):
public static void main(String[] args) {
String jsonStr = """
{
"attributes":[
{
"name":"some name",
"value":"some value"
}
]
}""";
Gson gson = new Gson();
Type mapStrByStr = new TypeToken<Map<String, List<Attribute>>>(){}.getType();
Map<String, List<Attribute>> map = gson.fromJson(jsonStr, mapStrByStr);
System.out.println(map);
}
}
public static class Attribute{
private String value;
private String name;
@Override
public String toString() {
return "Attribute{"
"value='" value '\''
", name='" name '\''
'}';
}
}
Output:
{attributes=[Attribute{value='some value', name='some name'}]}