【问题标题】:How to parsing JSON like this?如何像这样解析 JSON?
【发布时间】:2017-09-13 02:13:17
【问题描述】:

我有像

这样的 json 数据格式
{
   "status":200,
   "message":"ok",
   "response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
   }
}

我想获取 values 数组的一个值并将其放在 Eclipse 中的 textView 上。在eclipse中查看我的代码

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

【问题讨论】:

  • 您的代码似乎缺少某些部分。 try 在哪里,函数在哪里关闭?

标签: java android eclipse jsonparser


【解决方案1】:

您可以使用 GSON

为您的响应创建一个 POJO

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

   // create SET's and GET's
}

然后使用 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();
  }
}

【讨论】:

  • 非常感谢 joao86,您的代码对我有帮助,这是可行的,但我想按索引获取值数组。我该怎么办?请
  • @ahsanasha07 get values array by index. 是什么意思?如果要获取数组某个位置的值,只需p.getValues().get(position)
  • 是的,先生,我想在数组的某个位置获取值。我尝试 p.getValues().get(position) 不起作用。
  • 使用时会发生什么?
  • 当我运行项目时,应用程序自行关闭
【解决方案2】:

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

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

如果您知道 json 是 JSONObject 类的实例,则可以使用 readTree,否则使用 typeref 并使用 readValue 来获取地图。

【讨论】:

    【解决方案3】:
        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(); 
        }
         }
    

    【讨论】:

    • 谢谢兄弟,现在正在工作。我只是改变 tv.setText(jarr.get(0).toStirng(1));进入 tv.setText(jarr.get(0).toString());完成
    • 如果有帮助,你可以给我投票。或将其标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多