如何解析这样的JSON?

问题描述:

我有这样如何解析这样的JSON?

{ 
    "status":200, 
    "message":"ok", 
    "response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0] 
    } 
} 

我想获取值数组的一个值,并把它的TextView在Eclipse JSON数据格式。看看我在eclipse中的代码

protected void onPostExecute (String result){ 
try { 
JSONobject json = new JSONObject(result); 
tv.setText(json.toString(1)); 
}catch (JSONException e){ 
e.printStackTrace(); 
} 
} 
+2

您的代码似乎缺少某些部分。 “try”在哪里?功能在哪里关闭? – nalyd88

您可以使用jackson库进行json解析。

ObjectMapper mapper = new ObjectMapper(); 
Map map = mapper.readTree(json); 
map.get("key"); 

您可以使用readTree如果你知道JSON是JSONObject的其他类使用typeref的实例,并与readValue去获取地图。

您可以使用GSON

您的回复

public class Response{ 
    private int result; 
    private double time; 
    private ArrayList<Integer> values; 

    // create SET's and GET's 
} 

创建一个POJO然后用GSON创建你的愿望的对象。

protected void onPostExecute (String result){ 
    try { 
    Gson gson = new GsonBuilder().create(); 
    Response p = gson.fromJson(result, Response.class); 
    tv.setText(p.getValues()); 
    }catch (JSONException e){ 
    e.printStackTrace(); 
    } 
} 
+0

非常感谢joao86的,你的代码已经帮了我,这是工作,但我想通过索引得到值数组。我该怎么做呢?请 –

+0

@ ahsanasha07你是什么意思'按值得到值数组。'?如果你想获得数组中某个位置的值,只需执行'p.getValues()。get(position)' – joao86

+0

是的,先生,我想获得数组中某个位置的值。我尝试p.getValues()。get(position)不起作用。 –

protected void onPostExecute (String result){ 
    try { 
    JSONObject json = new JSONObject(result); 
    JSONObject resp = json.getJSONObject("response"); 
JSONArray jarr = resp.getJSONArray("values"); 
    tv.setText(jarr.get(0).toString(1)); 
    }catch (JSONException e){ 
    e.printStackTrace(); 
    } 
    } 
+0

仍然无法正常工作 –

+0

感谢兄弟,现在正在工作。我只是改变tv.setText(jarr.get(0).toStirng(1)); into tv.setText(jarr.get(0).toString());完成 –

+0

如果有帮助,你可以投我一票。或者将其标记为已回答。 –