简体   繁体   中英

Java JSONObject from JSONArray gets error

I have a simple Json string as a JSONArray like this:

[{"id_group":"19","state_active":"1","title":"hello world","token":"55811d9184921469"}]

I'm trying to get title object with this code:

JSONObject title =  jsonArray.getJSONObject(0).getJSONObject("title");

To update that with other value of title key by:

title.put("title","sample updated string");

I get this error:

title of type java.lang.String cannot be converted to JSONObject

For this line

JSONObject title =  jsonArray.getJSONObject(0).getJSONObject("title");

JSONObject contains key and value . In your case title is key in JSONObject . Do something like this...

JSONObject title =  jsonArray.getJSONObject(0);
title.put("title","sample updated string");

title is not a JSON Object it's a key in key-Value pair so you can not fetch it by using

getJSONObject("title");

Instead you should do something like this

JSONObject outerJson=jsonArray.getJSONObject(0);
String title =outerJson.getString("title"); //Existing title Value
//Now Modifying title 
title="New Title";
outerJson.put("title",title);

因此,您的错误声明为:title是String ,而不是JSONObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM