I am trying to convert multiple objects of the same type into a List
in Java. For example, my json would be:
{
"Example": [
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
{
"foo": "a3",
"bar": "b3",
"fubar": "c3"
}
]
}
I have a class:
public class Example {
private String foo;
private String bar;
private String fubar;
public Example(){};
public void setFoo(String f){
foo = f;
}
public void setBar(String b){
bar = b;
}
public void setFubar(String f){
fubar = f;
}
...
}
I want to be able to turn the json string I get into a list of Example
objects. I would like to do something like this:
JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
List<Example> result = parser.parse(List.class, json);
Doing this I get an error:
Cannot set property Example on class java.util.ArrayList
i have a jsonstring like this :
and convert it to list by this snippet of code:
i use net.sf.json-lib jar file.
I solved it by modifying my JSON to be in the form:
Then I used the java code:
You cannot convert this json to
List
but you can convert this toMap
.See your json
String
:Here "Example" is key(String) and value is List object of Example.
Try this:
Full code of
Example
:OutPut: