我希望有人可以告诉我我做错了什么......
我使用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吗?
非常感谢任何帮助。
亲切的问候 弗朗索瓦
答案 0 :(得分:2)
您在两个示例中显示的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对象。这实际上是 lot 更简单:
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);