- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望有人能告诉我哪里做错了......
我使用 sendgrid 进行电子邮件跟踪,它发布如下 JSON:
[
{
"email": "john.doe@sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
现在我想获取“timestamp”的值,例如 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无效。 "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;
}
因为您有这些数组,所以您想使用 TypeToken
和Type
指示您的 JSON 是 List
其中ResponseObject
对象:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
关于java - 使用 GSON 从 Java 中的 JSON 字符串获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23236792/
我是一名优秀的程序员,十分优秀!