Question

I hope someone can show me where i'm doing it wrong...

I'm using sendgrid for my email tracking and it is posting a JSON like the following:

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

Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:

      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();

The string of jsonString gives me the following which i think is in the right format:

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

But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);

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

What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?

Any help would be very much appreciated.

Kind regards Francois

Était-ce utile?

La solution

The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"

Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):

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

If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).

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

Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:

JsonArray myArray = je.getAsJsonArray();

You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:

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);
}

Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:

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

Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:

Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top