【问题标题】:How to parse json from using gson如何使用 gson 解析 json
【发布时间】:2017-08-05 14:33:24
【问题描述】:

我有这个 json 数据,我想得到 "fine" -> "start_time" 值。 我正在使用 Gson,我只是想知道简单的方法。

{
  "result_index": 0,
  "results": [
{
  "final": true,
  "alternatives": [
    {
      "confidence": 0.715,
      "transcript": "hello how are you holds the medically I hope you are fine "
    }
  ],
  "keywords_result": {
    "fine": [
      {
        "normalized_text": "fine",
        "start_time": 5.85,
        "end_time": 6.27,
        "confidence": 0.918
      }
    ]
  }
}
]
}

【问题讨论】:

标签: java parsing gson


【解决方案1】:

亲爱的朋友,你好,

  • 您可以为此目的使用 Jackson。假设这是一个 Maven 项目,您可以添加依赖项:

    com.fasterxml.jackson.core 杰克逊数据绑定 2.6.3

然后您可以使用 jackson 库并将 json 字符串解析为您的相关对象,在这种情况下,您可以像这样定义您的 pojo:

public class Staff {
    private int result_index;
    private List<Result> results;
    //getters & setters
}
public class Result {
    private boolean final;
    private List<Alternative> alternatives;
    private KeywordsResult keywords_result;
    //getters & setters

}

public class Alternative{
    public double confidence;
    public String transcript;
    //getters & setters
}
public class KeywordsResult{
    private List<Fine> fine;

}
public class Fine{
    private String normalized_text;
    private double start_time;
    private double end_time;
    private double confidence;
    //getters & setters
}

public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            // Convert JSON string to Object
            String jsonInString = "{\\r\\n  \\\"result_index\\\": 0,\\r\\n  \\\"results\\\": [\\r\\n{\\r\\n  \\\"final\\\": true,\\r\\n  \\\"alternatives\\\": [\\r\\n    {\\r\\n      \\\"confidence\\\": 0.715,\\r\\n      \\\"transcript\\\": \\\"hello how are you holds the medically I hope you are fine \\\"\\r\\n    }\\r\\n  ],\\r\\n  \\\"keywords_result\\\": {\\r\\n    \\\"fine\\\": [\\r\\n      {\\r\\n        \\\"normalized_text\\\": \\\"fine\\\",\\r\\n        \\\"start_time\\\": 5.85,\\r\\n        \\\"end_time\\\": 6.27,\\r\\n        \\\"confidence\\\": 0.918\\r\\n      }\\r\\n    ]\\r\\n  }\\r\\n}\\r\\n]\\r\\n}";
            Staff json2Object = mapper.readValue(jsonInString, Staff.class);
            // do whatever you want with object
        }catch (Exception e){
            // handle exception
        }
    }
  • 最后,您的对象已准备好获得您想要的任何道具,一旦实施您的 pojo,就再也不会出现问题了!

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 1970-01-01
    • 2011-02-12
    • 2012-01-02
    • 1970-01-01
    • 2014-05-10
    • 2015-07-10
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多