2017-08-05 128 views
-4

我有这个json数据,我想要“好” - >“start_time”值。 我使用Gson,我只是想知道简单的方法。如何从使用gson解析json

{ 
    "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 
     } 
    ] 
    } 
} 
] 
} 
+0

看看这个:https://stackoverflow.com/questions/5490789/json-parsing-using-gson-for-java – goblinjuice

+0

你试过什么? –

+0

[使用Gson for Java进行JSON解析]的可能重复(https://stackoverflow.com/questions/5490789/json-parsing-using-gson-for-java) – mgyongyosi

回答

0

你好亲爱的朋友,

  • 您可以使用杰克逊用于此目的。假设这是一个Maven项目,你可以添加具有相关性:

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

然后你就可以使用杰克逊库和解析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并且再也不会有问题了!