如何使用gson解析json

时间:2017-08-05 14:33:25

标签: java parsing gson

我有这个json数据,我想得到"罚款" - > " 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
      }
    ]
  }
}
]
}

1 个答案:

答案 0 :(得分:0)

你好亲爱的朋友,

  • 您可以将杰克逊用于此目的。假设这是一个maven项目,您可以添加依赖项:

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

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

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并且再也不会有问题了!