java - 解析没有键的Json数组

标签 java android arrays json parsing

我想从服务器解析一个数组,但我无法获取该数组 这是成功获取的 jsonString :

{
    "status":"OK",
    "message":"this is your start and end coordinates",
    "data":"{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}

我想要数据数组列表中的 double 值:

//try/catch
Log.d(TAG, "Passes here");          
JSONObject jObject = new JSONObject(jsonString);

JSONArray jData = jObject.getJSONArray("data");
Log.d(TAG, "Not PAASING HERE !!! ");

JSONArray jArrayStart = (JSONArray) jData.get(0);
JSONArray jArrayEnd =  (JSONArray) jData.get(1);

latitudeStart =  (Double) jArrayStart.get(0);
longtitudeStart = (Double) jArrayEnd.get(1);
latitudeEnd = (Double) jArrayEnd.get(0);
longtitudeEnd = (Double) jArrayEnd.get(1);

最佳答案

您要解析的是一个字符串

{
    "status": "OK",
    "message": "this is your start and end coordinates",
    "data": "{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}

所以它是这样工作的:

//first, retrieve the data from the response JSON Object from the server
JSONObject response = new JSONObject(jsonString);
String status = response.getString("status");
String message = response.getString("message");
//Note this: "data" is a string as well, but we'll have to parse that later.
String data = response.getString("data");

//get the doubles from the arrays from the "data" component.
JSONObject dataObject = new JSONObject(data);
JSONArray start = dataObject.getJSONArray("start");
JSONArray end = dataObject.getJSONArray("end");

for (int i = 0; i < start.length(); i++) {
    String value = start.getString(i);
    //do something with the start String (parse to double first)
}
for (int i = 0; i < end.length(); i++) {
    String value = end.getString(i);
    //do something with end String (parse to double first)
}

所以数据实际上是一个 String,但表示一个 JSONObject(您必须解析它),而它又包含两个 JSONArray

如果 dataJSONObject 而不是 String,则 JSON 将如下所示:

{
    "status": "OK",
    "message": "this is your start and end coordinates",
    "data": {
        "start": [
            "35.778763",
            "51.427360"
        ],
        "end": [
            "35.768779", //note that in your example, this quote is missing (first quote on next line too)
            "51.415002"
        ]
    }
}

关于java - 解析没有键的Json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25744408/

相关文章:

java - 执行 gae 时出现问题 :run using gae maven plugin

java - 如何缩短有关 Stringrequest 的代码?

android - Android中通过JSON解析多行数据

javascript - 通过减少和数组返回对象数组

ios - Afnetworking 延迟响应

Java 域对象

java - 如何将结构数组传递给函数以便在 JNA 中获取结果

java - 配置cygwin构建ndk项目

android - 如何创建响应式 ImageView?

c++ - 在c++ xll中从excel中接收一个矩阵,修改并返回