I have this Java class:
class A {
private B b;
class B {
private String a;
//getter + setter
}
}
This is the content of JSON file:
[{"b" : {"a": "Hello!"}},
{"b" : {"a": "Hi!"}},
{"b" : {"a": "Hello2!"}}]
I want to deserialize my JSON file into an ArrayList<A>
with the nested class inside. How can I do this?
You can simply achieve this with Gson.
package stackoverflow.questions.q18932252;
import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Q18932252 {
public static void main(String[] args){
String json = "[{\"b\" : {\"a\": \"Hello!\"}}, {\"b\" : {\"a\": \"Hi!\"}}, {\"b\" : {\"a\": \"Hello2!\"}}]";
Type listOfA = new TypeToken<List<A>>() {}.getType();
Gson g = new Gson();
ArrayList<A> result = g.fromJson(json, listOfA);
System.out.println(result);
}
}
With this result (I have added standard toString
methods):
[A [b=B [a=Hello!]], A [b=B [a=Hi!]], A [b=B [a=Hello2!]]]
Since you are asking about a JSON file, ie a text file that contains a JSON string, please make reference to How to create a Java String from the contents of a file question for loading a file into a string.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句