如何在json结果中获取高亮词并保存到列表中? java的

时间:2017-01-17 03:45:02

标签: java json

{
    "relevant": ["Lighthouse", "family", "house", "national Ranking", "national Years", "national Selection", "carbohydrate", "national Affiliation", "home Arena", "temp Place"],
    "result": [{
        "keyword": "And thank people mission American Homeland Department Security White Applause",
        "Sentence": "At the White House he has done an outstanding job.",
        "highlightTerm": ["house"]
    }, {
        "keyword": "And thank people mission American Homeland Department Security White Applause",
        "Sentence": "Welcome to the White House and welcome to this historic moment.",
        "highlightTerm": ["house","family"]

    }]
}

我想解析JSON结果以获取所有highlightTerm并将其保存到ArrayList中。

作为“highlightTerm”:[“house”,“family”]不是字符串,如何解析它?

   JSONArray result = jsonObject.getJSONArray("result");
     System.out.println("result is:: " + result);

      ArrayList<String> highlightTermlist = new ArrayList<String>();

      for (int i =0; i < result.length(); i++){

         // String Sentence = result.getJSONObject(i).getString("Sentence");

      JSONObject j = result.getJSONObject(i);
  System.out.println("jjjjjjjjjjjjjjjjjjjjjjjjjjjj:: " + j);

错误:

 ArrayList<String> highlightTermlist =result.getJSONObject(i).getArrayList("highlightTermlist");

1 个答案:

答案 0 :(得分:0)

你得到了一个Json数组并循环遍历它。

尝试使用以下代码..它将结果显示为

  

完成HighlightTerms列表 - [family,house]

使用JsonArray元素将列表转换为Json Object,如下所示。

  

{ “highlightTerm”:[ “房子”, “家”, “家庭”]}

如果您还想要重复值,请从设置更改为列表。

 JSONParser parser = new JSONParser();

 List<String> allHighlightItems = new ArrayList<>();

    try {
        Object obj = parser.parse(new FileReader(
                "sample.json"));

        JSONObject jsonObject = (JSONObject) obj;
        JSONArray results = (JSONArray)(jsonObject.get("result"));
        System.out.println("Complete Data list --"+results.toString());

        for(Object singleResult : results) {
            JSONObject singleArrayData = (JSONObject) singleResult;
            JSONArray highlightTermOfGivenResult = (JSONArray)singleArrayData.get("highlightTerm");
            for(Object singleHighlightTerm: highlightTermOfGivenResult){
                if(singleHighlightTerm != null) {
                    allHighlightItems.add(singleHighlightTerm.toString());
                }
            }
        }
        System.out.println("Complete HighlightTerms list --"+allHighlightItems.toString());

        JSONObject myJsonObject = new JSONObject();
        myJsonObject.put("highlightTerm",allHighlightItems);

        System.out.println("Complete HighlightTerms list --"+myJsonObject.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }