将字符串转换为JSON数组我从Web服务获得以下字符串的JSON,并尝试将其转换为 JSONarray{
"locations": [
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
}
]}我在String网上验证了这一点,似乎是正确的。现在我在android开发中使用以下代码来利用JSONArray jsonArray = new JSONArray(readlocationFeed);这会抛出异常类型不匹配的异常。
3 回答
暮色呼如
TA贡献1853条经验 获得超9个赞
在这里你得到JSONObject所以改变这一行:
JSONArray jsonArray = new JSONArray(readlocationFeed);
以下内容:
JSONObject jsnobject = new JSONObject(readlocationFeed);
之后
JSONArray jsonArray = jsnobject.getJSONArray("locations");for (int i = 0; i < jsonArray.length(); i++) { JSONObject explrObject = jsonArray.getJSONObject(i);}
慕神8447489
TA贡献1780条经验 获得超1个赞
输入字符串
[ { "userName": "sandeep", "age": 30 }, { "userName": "vivan", "age": 5 }]
将字符串转换为JSON的简单方法
public class Test{ public static void main(String[] args) throws JSONException { String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] "; JSONArray jsonArr = new JSONArray(data); for (int i = 0; i < jsonArr.length(); i++) { JSONObject jsonObj = jsonArr.getJSONObject(i); System.out.println(jsonObj); } }}
产量
{"userName":"sandeep","age":30}{"userName":"vivan","age":5}
MYYA
TA贡献1868条经验 获得超4个赞
使用json lib: -
String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";Object object=null;JSONArray arrayObj=null;JSONParser jsonParser=new JSONParser();object=jsonParser.parse(data);arrayObj=(JSONArray) object;System.out.println("Json object :: "+arrayObj);
使用GSON lib: -
Gson gson = new Gson();String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";JsonParser jsonParser = new JsonParser();JsonArray jsonArray = (JsonArray) jsonParser.parse(data);
添加回答
举报
0/150
提交
取消