如何使用Java删除JSONArray元素 [英] How to remove JSONArray element using Java

查看:3531
本文介绍了如何使用Java删除JSONArray元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

My JsonArray是

  [{
Id:null,
Name: 一项新任务,
StartDate:2010-02-03T05:30:00,
EndDate:2010-02-04T05:30:00,
Duration:1,
DurationUnit:d,
PercentDone:0,
ManuallyScheduled:false,
Priority:1,
parentId:8,
index:0,
depth:3,
checked:null},{
Id:null,
Name:New task,
StartDate:2010-02-04T05:30:00,
EndDate:2010-02-04T05:30: 00,
Duration:0,
DurationUnit:d,
PercentDone:0,
ManuallyScheduled:false,
优先级:1,
parentId:8,
index:1,
depth:3,
checked:null}]

现在从这个JsonArray中,我想删除Id,ManuallyScheduled,checked,

我尝试使用 jsonArray.remove(1)以及 jsonArray.discard(Id) in JAVA。
但没有任何反应。什么是我做错了删除数组项目?



我使用JAVA作为我的技术。

方案

你在那里有一个对象数组。因此,您必须遍历数组并从每个对象中移除必要的数据,例如

  for(int i = 0,len = jsonArr.length(); i< len; i ++){
JSONObject obj = jsonArr.getJSONObject(i);
//做你的移除
obj.remove(id);
//等等
}

我假设您正在使用 org.json.JSONObject org.json.JSONArray 在这里,但是无论JSON处理库如何,如果你想转换像 [{id:215},{id:216}] [215,216] 你可以这样:

  JSONArray intArr = new JSONArray(); 
for(int i = 0,len = objArr.length(); i< len; i ++){
intArr.put(objArr.getJSONObject(i).getInt(id));
}


My JsonArray is

[{
"Id": null,
"Name": "One New task",
"StartDate": "2010-02-03T05:30:00",
"EndDate": "2010-02-04T05:30:00",
"Duration": 1,
"DurationUnit": "d",
"PercentDone": 0,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": 8,
"index": 0,
"depth": 3,
"checked": null },{
"Id": null,
"Name": "New task",
"StartDate": "2010-02-04T05:30:00",
"EndDate": "2010-02-04T05:30:00",
"Duration": 0,
"DurationUnit": "d",
"PercentDone": 0,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": 8,
"index": 1,
"depth": 3,
"checked": null }]

Now from this JsonArray I want to remove Id, ManuallyScheduled, checked,

I tried using jsonArray.remove(1) and also jsonArray.discard("Id") in JAVA. but nothing happens. what am I doing wrong to remove array items?

I am using JAVA as my technology.

解决方案

What you have there is an array of objects. Therefore you'll have to loop through the array and remove the necessary data from each object, e.g.

for (int i = 0, len = jsonArr.length(); i < len; i++) {
    JSONObject obj = jsonArr.getJSONObject(i);
    // Do your removals
    obj.remove("id");
    // etc.
}

I've assumed you're using org.json.JSONObject and org.json.JSONArray here, but the principal remains the same whatever JSON processing library you're using.

If you wanted to convert something like [{"id":215},{"id":216}] to [215,216] you could so something like:

JSONArray intArr = new JSONArray();
for (int i = 0, len = objArr.length(); i < len; i++) {
    intArr.put(objArr.getJSONObject(i).getInt("id"));
}

这篇关于如何使用Java删除JSONArray元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆