Parsing JSON String as simple as possible with GSO

2019-09-21 05:03发布

问题:

Using GSON, how can i return a single key from a Multidimensional Json String?

Here is the Multidimensional Json String:

{"statusCode":0,"statusDescription":"OK","data":{"user":{"id":xxx,"company_id":xxx,"account_type":"5","enable_locations":true,"intuit_user_id":null,"nick_name":"xxx","is_owner":"1","enabled":"1"},"session_token":"xxx"}}

I want to return the "session_token" key value.

I'm trying this:

class app {
    static class Response {
        String session_token;
    }
    public void getSessionToken() {

        String x = {"statusCode":0,"statusDescription":"OK","data":{"user":{"id":xxx,"company_id":xxx,"account_type":"5","enable_locations":true,"intuit_user_id":null,"nick_name":"xxx","is_owner":"1","enabled":"1"},"session_token":"xxx"}}
        Response r = new Gson().fromJson(x, Response.class);
        System.out.println(r.session_token);
    }
}

But with this, my r.session_token returns null.

回答1:

You would need to use Gson's JsonParser class directly and extract the data from the parse tree:

String myJsonString = "{\"name\":\"john\",\"lastname\":\"smith\"}";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(myJsonString); 
JsonObject jsonObject = element.getAsJsonObject();
String lastName = jsonObject.get("lastname").getAsString();
System.out.println(lastName);

That said, it's debatable whether this would save you any real time over:

(edited from comments below):

class App {

    static class Response {
        String lastname;
    }

    public static void main(String[] args) {
        String myJsonString = "{\"name\":\"john\",\"lastname\":\"smith\"}";
        Response r = new Gson().fromJson(myJsonString, Response.class);
        System.out.println(r.lastname);
    }
}

Gson will silently ignore the fact that there's more data in the JSON than you're interested in, and later on you might be interested in it, in which case it's trivial to add fields to your Response class.

Edit due to question changing:

You have a JSON object. It contains a field data whose value is an object. Inside that object you have a field session_token that you're interested in.

Either you have to navigate to that field through the parse tree, or you have to create Java classes that all will map to. The Java classes would resemble (at the bare minimum):

class Response {
    Data data;
}

class Data {
    String session_token;
}


标签: java json gson