1
我从JSON字符串生成JAVA对象。但是我在迭代列表项时遇到了问题。这个JSON是一个嵌套数组。这是我的Java代码如何迭代由GSON制作的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)\"" +
" }]" +
"}]";
当我运行上面的代码只显示在关卡的儿童中。但是我想迭代整个对象列表。
有什么想法?请帮忙。
这很好,但当我更改JSON字符串,就像我添加更多的孩子,并使其更加嵌套时,它再次只显示我2个孩子。我的json是动态生成的,可以达到用户想要的尽可能多的孩子。 – user2777070
你可以发布更多的孩子json吗?从你的代码'Employees emp = l.get(0);'我们只使用第一个孩子,所以... –
我改变了我的代码,现在试试,运行所有的孩子 –