我的jsonobject
如下所示
{
"TopLevelDomainList": {
"TopLevelId": "01",
"DomainName": "List of Domains for e-Governance",
"APIVersion": "1.0",
"ListVersion": "1.1",
"ListVersionDate": "1/10/2015 12:30:50",
"Banner": {
"Image": "http://localhost/image/logo.jpg"
},
"Footer": {
"Image": "http://localhost/image/footer.jpg"
},
"ParticipatingDomains": [
{
"Id": "1",
"DomainName": "toplevel1",
"Location": "http://toplevel.com",
"Icon": "http://toplevel.com"
},
{
"Id": "2",
"DomainName": "toplevel2",
"Location": "http://toplevel.com",
"Icon": "http://toplevel.com"
}
]
}
}
我在这里写java代码我想要的是ss或
ja =[{id:1,name:toplevel},{id:2,name:toplevel2}]
JSONObject objj = firstSport.getJSONObject("TopLevelDomainList");
String ob = objj.getString("TopLevelId");
System.out.println("ob is !!!=>"+ob);
if(firstSport.has("TopLevelDomainList"))
{
count=1;
obj1 = objj.getJSONArray("ParticipatingDomains");
System.out.println("obj value is ===>"+obj1.length());
for (int i = obj1.length()-1; i >=0; i--) {
JSONObject rec = obj1.getJSONObject(i);
Id = rec.getString("Id");
System.out.println("id is !!!!!!!!!!!!!!!!!!!!!!"+Id);
Name = rec.getString("DomainName");
banobj.put("Id", Id);
banobj.put("DomainName", Name);
banobj.put("HasChildren", "true");
ja.put(banobj);
System.out.println("ja is ===> "+ja);
System.out.println("banobj1 value is !!!!"+banobj);
}
ss=ja.toString();
System.out.println("ss is ===> "+ss);
现在我得到的是ja或ss值
[{id:2,name:toplevel2},{id:2,name:toplevel2}]
如果我正在尝试反向for循环,也会获得与ja数组1相同的值,而不是2;
答案 0 :(得分:0)
您似乎正在为要放入数组的每个元素使用相同的 banobj(相同的引用),因此您只需 ovveride 其值周期。
尝试使用类似
的内容 banobj.put("Id", Id);
banobj.put("DomainName", Name);
banobj.put("HasChildren", "true");
ja.put(banobj);
banobj = new BanObj(); // I don't know what should be here exaclty
答案 1 :(得分:0)
谢谢,所以我需要添加元素,如果我把数据覆盖现有数据。现在我正在使用JsronArrayBuilder和JsonObjectBuilder来添加元素。它的工作正常。 JsonArrayBuilder builder1 = Json.createArrayBuilder(); JsonObjectBuilder builder = Json.createObjectBuilder();
for(int i=0;i<obj1.length();i++){
JSONObject rec = obj1.getJSONObject(i);
Id = rec.getString("Id");
Name = rec.getString("DomainName");
builder.add("Id",Id)
.add("DomainName", Name)
.add("HasChildren", "true");
builder1.add(builder);
} empObj=builder1.build();
ss=empObj.toString();