2016-08-18 14 views

回答

1
JSONObject mainJsonObject = yourJsonObject.getJSONObject("main"); 
float pressure = mainJsonObject.getFloat("pressure"); 
float tempMin = mainJsonObject.getFloat("temp_min"); 
float tempMax = mainJsonObject.getFloat("temp_max"); 
0
String jsonString = ... //Your json string 
JSONObject jsonObject = new JSONObject(jsonString); 
JSONObject mainObject = jsonObject.getJSONObject("main"); 
double temp = mainObject.getDouble("temp"); 
//And get other fields just like the line above. 


您还可以使用 Gson库,这使得解析jsons超级简单。

首先根据自己的JSON定义你的模型:

public class JSON { 
    public Main main; 
    //...  

    public static class Main { 
     public double temp; 
     public int pressure; 
     //... 
    } 
} 

然后使用Gson解析JSON字符串:

JSON object = new Gson().fromJson(jsonString, JSON.class); 
double temp = object.main.temp; 
0

首先你的JSON模式复制到JsonUtils生成您模型(类) ,然后你可以很容易地使用Gson来解析你的json并将它反序列化到你的类中。

例如,你可以看到这个Gson Tutorial

0

您需要获得root JSON对象,然后让你的嵌套的“主”对象。

如果你提供你的JSON文件会更好。但是有树结构,代码应该看起来像这样:

//Doing it inside try/catch block, because it may throw JSONException 
    try{ 
     //Getting root JSON object 
     JSONObject rootJSON = new JSONObject(s); 
     //Getting nested "main" object from root object 
     JSONObject mainJSON = rootJSON.getJSONObject("main"); 
     //Getting custom String from JSON object, say "temp" 
     String ourString = ourObject.getString("temp"); 
     //Then you can use it whatever way you want 
     Log.e("JSONObject", ourString); 
    //Handling JSONException 
    } catch(JSONException e) { 
     e.printStackTrace(); 
    } 
相关问题