【问题标题】:How to read json file into java with GSON library如何使用 GSON 库将 json 文件读入 java
【发布时间】:2017-03-01 09:51:45
【问题描述】:

我想使用 GSON 库用 java 读取这个 JSON 文件。 我是使用 gson libray 的新手。有人请更正我的代码 我的 JSON 文件如下所示:

{  
"tableRows":[  
  {  
     "id":"100",
     "mailContent":"Test mail content 123",
     "sentiment":"0"
  },
  {  
     "id":"200",
     "mailContent":"Test mail content 123",
     "sentiment":"0"
  },
  {  
     "id":"300",
     "mailContent":"Test mail content 123",
     "sentiment":"0"
  }
 ]
}

这是我为读取此文件而编写的 java 代码:

import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonObject;
public class Sample {
 public static void main(String[] args) {

     JsonParser parser = new JsonParser();
     try { 
        JsonElement jsontree = parser.parse(
            new FileReader(
                "/Users/kesavan-4688/Desktop/JSP-Eclipse/Sample/src/Demo/sample.json"
            )
        );
        JsonElement je = jsontree.getAsJsonObject();
        JsonArray ja = je.getAsJsonArray();
        for (Object o : ja)
        {
            JsonObject person = (JsonObject) o;

            String id = person.get("id").getAsString();
            System.out.println(id);

            String mail = person.get("mailcontent").getAsString();
            System.out.println(mail);

            String sentiment = person.get("sentiment").getAsString();
            System.out.println(sentiment);
        }   
     }  
     catch (JsonIOException e) {
        e.printStackTrace();
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
 }

 }

但我得到以下异常:

Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at Demo.Sample.main(Sample.java:18)

【问题讨论】:

标签: java json gson


【解决方案1】:

您尝试将JsonObject 转换为无法工作的JsonArray,您需要先获取根JsonObject,然后使用getAsJsonArray(String memberName) 将属性tableRows 作为JsonArray 获取为下一个:

...
// Get the root JsonObject
JsonObject je = jsontree.getAsJsonObject();
// Get the property tableRows as a JsonArray
JsonArray ja = je.getAsJsonArray("tableRows");
for (Object o : ja) {
    ...
    // Warning JSON is case sensitive so use mailContent instead of mailcontent
    String mail = person.get("mailContent").getAsString();
    ...
}

输出:

100
Test mail content 123
0
200
Test mail content 123
0
300
Test mail content 123
0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多