将字符串转换为JSON数组


90

我具有来自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);

这会引发异常和类型不匹配的异常。


什么是数据类型readlocationFeed
IgorGanapolsky '16

1
@IgorGanapolsky,字串
Andrew

Answers:


160

在这里,您得到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);
}

注意,JSONObject的构造函数看起来已过时,并且在版本1.1.1中不支持将String作为参数
ankitkpd

jsnobject可能是jsonobject-拼写:)
DragonFire

41

输入字符串

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

23

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

这将不适用于Google GSON吗?你能帮忙吗?
2015年

@pashtika ..请解释您的问题..那我可以尝试一下。
Aravind Cheekkallur,2015年

@pashtika ..是的,您可以使用GSON jar并将字符串转换为json
Aravind Cheekkallur,2015年

3
在第二个代码段中似​​乎有一个错误,因为该gson对象已创建但未使用。
Dev-iL 2015年

只需忽略第一行。它可以解决问题 Gson gson = new Gson();
fritz-playmaker

16

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

JSONObject jsonObject = new JSONObject(readlocationFeed);

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

字符串操作是从另一个角度思考的一种好方法-关于这个问题
DragonFire

4

尝试这段代码:

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

3

如果响应是这样的

"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循环来获取值。


1

您可以执行以下操作:

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

1

这是一种非常简单的转换方式:

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

}


1
请通过添加上下文作为文本而不是注释来改善您的回答。
理查德·埃里克森

0

如果具有来自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数组接受,然后在读取其Object时必须使用Object Mapper.readValue,因为Json Object Still in String。

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

    }

如果您使用mapper.convert(param,param),则mapper.read是正确的函数。这会给你错误。


我有上面的JSON,我需要使用Gson实现上述任务。我该怎么办?
碧山
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.