【问题标题】:Parsing JSON correctly in Android Studio?在 Android Studio 中正确解析 JSON?
【发布时间】:2016-04-01 22:02:29
【问题描述】:

好吧,对 Android Studio 来说是全新的,但我一直在尝试在 Android Studio 中解析 pack.tf 的 json,但我有点卡住了。

这是我尝试解析的 json 的小 sn-p:

{
"response": {
    "success": 1,
    "current_time": 1448658000,
    "items": {
        "A Color Similar to Slate": {
            "last_updated": 1448654419,
            "quantity": 48,
            "value": 99
        },

我用来解析 JSON 的代码在这里:

   String finalJSON = buffer.toString();
   JSONObject parentObject = new JSONObject(finalJSON);
   JSONArray parentArray = parentObject.getJSONArray("A Color Similar to Slate");

  JSONObject finalObject = parentArray.getJSONObject(3);

  int price = finalObject.getInt("value");

  return "$" + price;

非常感谢!

【问题讨论】:

  • 是否允许使用 Gson 库?
  • 您可以使用 gson 或 jackson 类型的 util lib。
  • 我从未听说过 GSON!有没有好的教程可以检查一下?
  • 可能是github上的文档;)看看我的回答
  • 你卡在哪里了?请更具体。

标签: java android json android-studio


【解决方案1】:

1) 创建一些(自定义,根据您的需要调整)Model 类

public class Model {
    private String title;
    private List<String> authors;
//getters fields, magic ...
}

2) 解析您的 JSON (

public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json";

Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
Model model = gson.fromJson(br, Model.class);

或

1) 使用 JSON Parser 解析它

BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(br).getAsJsonObject();

两种方式都需要GSON库https://github.com/google/gson

【讨论】:

  • 这没有回答他的具体问题。他不妨去看看其他 GSON 的例子。我也喜欢 GSON,但我讨厌它自动成为任何 JSON 解析问题的答案。第三方库并不总是正确的答案。
  • 我提出了一种解决方案。可能不是最好的,但它解决了 OP 问题。如果会有另一种解决方案,我会给它+1,如果它也能工作并且它是否合适
  • 我不确定是否要实现这个,我已经构建了一个 JSONTask 类,来获取 JSON 文件,我只需要解析它。
  • 可以作为模型使用吗?
【解决方案2】:

试试这个:

你有 JSON:

   {"response":{
        "success": 1,
                "current_time": 1448658000,
                "items": {
            "A Color Similar to Slate": {
                "last_updated": 1448654419,
                        "quantity": 48,
                        "value": 99
            },
        }
    }
    }

代码:

  String finalJSON =buffer.toString();;
    JSONObject parentObject = null;
    try {
        parentObject = new JSONObject(finalJSON);
        JSONObject objectA_Color=parentObject.getJSONObject("response").getJSONObject("items").getJSONObject("A Color Similar to Slate");

       int  value=objectA_Color.getInt("value");
    } catch (JSONException e) {
        e.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多