【问题标题】:Getting the values from a JSON string in Java using GSON使用 GSON 从 Java 中的 JSON 字符串中获取值
【发布时间】:2014-06-07 20:14:07
【问题描述】:

我希望有人能告诉我我做错了什么......

我正在使用 sendgrid 进行电子邮件跟踪,它正在发布如下 JSON:

[
  {
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337966815,
    "event": "click",
    "url": "http://sendgrid.com"
    "userid": "1123",
    "template": "welcome"
  }
]

现在我想获取例如“时间戳”的值,即 1337966815 。我尝试了以下方法:

      StringBuffer jb = new StringBuffer();
      String line = null;
      try {
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null)
          jb.append(line);
      } catch (Exception e) { /*report an error*/ }
      String jsonString = jb.toString();
      Gson gson = new Gson();
      JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
      String timeStam = jsonObject.get(timestamp).toString();

jsonString 的字符串给了我以下我认为正确的格式:

[  {    "email": "john.doe@sendgrid.com",    "timestamp": 1337966815,    "event": "click",    "url": "http://sendgrid.com"    "userid": "1123",    "template": "welcome"  }]

但我在这行代码中遇到以下错误 - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52

我做错了什么?是jsonString的格式混淆了JsonObject吗?

非常感谢任何帮助。

亲切的问候 弗朗索瓦

【问题讨论】:

  • 你的 json 完整吗?因为它看起来像那些 '[' 和 ']' 的 jsonArray。
  • 您的 JSON 无效,它会告诉您这一点。除此之外,您首先如何使用 Gson 是值得怀疑的。如果您想要 JsonObject 而不是到 POJO 的映射,请参阅 stackoverflow.com/questions/4110664/…
  • 感谢 Brian 和 Amrut 的回复。是的,它是一个完整的 JSON。我想我错过了 JSONParser,我会尝试一下。
  • 这是一个 JSON 数组,而不是 JSON 对象,那么为什么要尝试反序列化为 JsonObject?另外,为什么要费力把它全部喝完然后把它交给Gson? Gson 可以为您做到这一点
  • 嗨,fge,你是什么意思? gson 不需要字符串吗?

标签: java json string gson


【解决方案1】:

您在两个示例中显示的 JSON 无效"url":"http://sendgrid.com"后面少了一个逗号

忽略这一点,您显示的 JSON 是 JSON 对象数组,而不是对象。这就是[] 的含义(更正缺少的逗号):

[
  {
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337966815,
    "event": "click",
    "url": "http://sendgrid.com",
    "userid": "1123",
    "template": "welcome"
  }
]

如果您没有将此 JSON 映射到 Java POJO,那么您可能希望使用 Gson 的 JsonParser 将您的 String 解析为 JsonElement(请注意,您甚至可以使用它直接从 Stream 中解析,但是如果你现在有你的代码的话)。

JsonElement je = new JsonParser().parse(jsonString);

现在您有了所谓的“分析树”。这个JsonElement 是根。要将其作为数组访问,您将执行以下操作:

JsonArray myArray = je.getAsJsonArray();

你只展示了这个包含一个对象的数组,但是假设它可以有多个。通过遍历数组,您可以:

for (JsonElement e : myArray)
{
    // Access the element as a JsonObject
    JsonObject jo = e.getAsJsonObject();

    // Get the `timestamp` element from the object
    // since it's a number, we get it as a JsonPrimitive
    JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");

    // get the primitive as a Java long
    long timestamp = tsPrimitive.getAsLong();
    System.out.println("Timestamp: " + timestamp);
}

意识到 Gson 主要 用于对象关系映射,您希望在其中获取 JSON 并将其转换为 Java 对象。这实际上是 很多 更简单:

public class ResponseObject {
    public String email;
    public long timestamp;
    public String event;
    public String url;
    public String userid;
    public String template;
}

因为您有这些数组,所以您想使用 TypeTokenType 来指示您的 JSON 是这些 ResponseObject 对象中的 List

Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多