Reading a JSON reply from WeatherUnderground

江枫思渺然 提交于 2019-11-29 17:57:49

You don't seem to understand what Gson does. It's a JSON parser, specifically one that will deserialize JSON to a Java POJO.

In your code you have:

String wdf = g.fromJson(message, String.class);

You're telling Gson to deserialize the JSON to a Java String object. It can't do that; your JSON isn't a String object - it's a big JSON object returned from Weather Underground. You already have a Java String (message) that contains the JSON text itself.

You either need to create a POJO that the JSON can be deserialized to, or pick the parts out of the JSON you want using Gson's parser and associated objects/methods.

Here's the start of what a POJO would look like (all fields public with no getters/setters just to make this example small):

class MyWUPojo {
    public Response response;
    // more after this that match the JSON
}

class Response {
    public String version;
    public String termsofservice;
    public Map<String, Integer> features;
}

You'd then deserialize the JSON into an instance of MyWUPojo with:

MyWUPojo wup = new Gson().fromJson(message,MyWUPojo.class);

If you didn't want to go the POJO route you could parse the JSON then get what you want from it:

JsonObject o = (JsonObject) new JsonParser().parse(message);

Now you' can use the various methods of JsonObject to access the parsed JSON. (See: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonObject.html )

The GSON User's Guide is pretty well written and explains this and more in great detail.

Edit to add: That null at the end of your JSON is caused by this:

while(message!=null){
    message = reader.readLine();
    buf.append(message);
}

You append null then the loop exits. It needs to be:

while ((message = reader.readline()) != null) {
    buf.append(message);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!