我正在从 JSON 字符串生成 JAVA 对象。但是我在迭代列表项时遇到了问题。这个 JSON 是一个嵌套数组。这是我的java代码
response.setContentType("text/html");
PrintWriter out = response.getWriter();
nString xr = request.getParameter("JSONString");
Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<List<EmployeeJSONObj>>(){}.getType();
List<EmployeeJSONObj>l = gson.fromJson(xr, type);
List<EmployeeJSONObj>l1 = l.get(0).getChild();
for(int i=0;i<l1.size();i++)
{
out.println("Name: "+l1.get(i).getName()+"<br/>");
}
并且我的 java 自定义类是
public class EmployeeJSONObj {
private String name;
private List<EmployeeJSONObj> children = new LinkedList<>();
EmployeeJSONObj()
{
}
public String getName()
{
return name;
}
public List<EmployeeJSONObj> getChild()
{
return children;
}
public String toString() {
return "name: " + name + ", children = " + children;
}
}
和 JSON 字符串来自 HTML 隐藏字段,这是我的 json 字符串
String str = "[{" +
" \"name\": \"3214657890RootSAPSSE\"," +
" \"children\": [{" +
" \"name\": \"672BENIAMEEN .Sales Base Market SectionCustomer Representative\"," +
" \"children\": [{" +
" \"name\": \"672BENIAMEEN .Sales Base Market SectionPeão\"," +
" \"children\": [{" +
" \"name\": \"910MAZHAR .Sales Base Market SectionCustomer Representative\"," +
" \"children\": [{" +
" \"name\": \"910MAZHAR .Sales Base Market SectionPeão\"," +
" \"children\": [{" +
" \"name\": \"713NOSHERWAN .Sales Sargodha SectionCustomer Representative\"," +
" \"children\": [{" +
" \"name\": \"713NOSHERWAN .Sales Sargodha SectionPeão\"" +
" }," +
" {" +
" \"name\": \"1161SAQLAIN .Sales Toba Taik Singh SecPeão\"" +
" }]" +
" }]" +
" }]" +
" }]" +
" }," +
" {" +
" \"name\": \"1161SAQLAIN .Sales Toba Taik Singh SecCustomer Representative\"," +
" \"children\": [{" +
" \"name\": \"1179SHAMOON .Administration SectionDriver ( R )\"" +
" }]" +
" }]" +
" }," +
" {" +
" \"name\": \"1179SHAMOON .Farooq Khan TrustDriver ( D)\"" +
" }]" +
"}]";
当我运行上面的代码时,它只显示在级别的孩子上。但我想迭代整个对象列表。
任何的想法?请帮忙。