Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

json - How to remove JSONArray element using Java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...