将字符串转换为 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);

This throws exception a type mismatch Exception.

558486 次浏览

您需要将给定的字符串转换为 JSONObject而不是 JSONArray,因为当前字符串包含 JsonObject作为根元素而不是 JsonArray:

JSONObject jsonObject = new JSONObject(readlocationFeed);

试试这段代码:

try {
Log.e("log_tag", "Error in convert String" + result.toString());
JSONObject json_data = new JSONObject(result);


String status = json_data.getString("Status");
{
String data = json_data.getString("locations");
JSONArray json_data1 = new JSONArray(data);
for (int i = 0; i < json_data1.length(); i++) {
json_data = json_data1.getJSONObject(i);


String lat = json_data.getString("lat");
String lng = json_data.getString("long");
}
}
}

Here you get JSONObject so change this line:

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);
}
String b = "[" + readlocationFeed + "]";
JSONArray jsonArray1 = new JSONArray(b);
jsonarray_length1 = jsonArray1.length();
for (int i = 0; i < jsonarray_length1; i++) {


}

或者在 JSONOBJECT 中转换它

JSONObject jsonobj = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsonobj.getJSONArray("locations");

使用 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);

如果回答是这样的话

"GetDataResult": "[{\"UserID\":1,\"DeviceID\":\"d1254\",\"MobileNO\":\"056688\",\"Pak1\":true,\"pak2\":true,\"pak3\":false,\"pak4\":true,\"pak5\":true,\"pak6\":false,\"pak7\":false,\"pak8\":true,\"pak9\":false,\"pak10\":true,\"pak11\":false,\"pak12\":false}]"

你可以这样解析

JSONObject jobj=new JSONObject(response);
String c = jobj.getString("GetDataResult");
JSONArray jArray = new JSONArray(c);
deviceId=jArray.getJSONObject(0).getString("DeviceID");

这里的 JsonArray 大小为1。否则,您应该使用 for 循环来获取值。

如果有以下来自 Web 服务的 JSON,JSON Array 作为响应:

       [3]
0:  {
id: 2
name: "a561137"
password: "test"
firstName: "abhishek"
lastName: "ringsia"
organization: "bbb"
}-
1:  {
id: 3
name: "a561023"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}-
2:  {
id: 4
name: "a541234"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}

必须首先接受它作为一个 Json 数组,然后在读取其对象时必须使用对象 Mapper.readValue,因为 Json 对象仍然在字符串中。

      List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);




for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
User usr = mapper.readValue(jsonObj.toString(), User.class);
list.add(usr);


}

Read 是正确的函数,如果你使用 mapper.Convert (param,param) ,它会给你一个错误。

你可以这样做:

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}

这是一个非常简单的转换方法:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;




class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;


public String getUsername() {
return username;
}


public void setUsername(String username) {
this.username = username;
}


public String getEmail() {
return email;
}


public void setEmail(String email) {
this.email = email;
}


public Integer getCredits() {
return credits;
}


public void setCredits(Integer credits) {
this.credits = credits;
}


public String getTwitter_username() {
return twitter_username;
}


public void setTwitter_username(String twitter_username) {
this.twitter_username = twitter_username;
}


@Override
public String toString() {
return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}

}

/*
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"hello@email.com","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"goodbye@email.com"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"mlsilva@email.com"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"fsouza@email.com"
* ,"credits":"1052","twitter_username":""}]
*/


public class TestaGsonLista {


public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

输入字符串

[
{
"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}