tags:

views:

52

answers:

1

I was wondering, given the following JSON, how I can produce a ResultSet instance, which carry Query valued ppb?

package jsontest;

import com.google.gson.Gson;

/**
 *
 * @author yccheok
 */
public class Main {

    public static class ResultSet {
        public String Query;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        final String s = "{\"ResultSet\":{\"Query\":\"ppb\"}}";
        System.out.println(s);
        Gson gson = new Gson();
        ResultSet resultSet = gson.fromJson(s, ResultSet.class);
        // {}
        System.out.println(gson.toJson(resultSet));
        // null?
        System.out.println(resultSet.Query);
    }
}

Currently, here is what I get :

{"ResultSet":{"Query":"ppb"}}
{}
null

Without modified the String, how can I get a correct Java object?

+2  A: 

Try first to construct a new object, call gson.toJson(object), and see the result.

I don't have gson, but jackson (another object-to-json mapper) prints this:

{"Query":"ppb"}

So, you don't include the class name. Actually, the gson user guide gives an example showing exactly this. Look at the BagOfPrimitives.

(And a final note - in Java, the accepted practice is that variables are lowercase - i.e. query rather than Query)

Update If you really can't change the json input, you can mirror the structure this way:

public static class Holder {
    public ResultSet ResultSet;
}

public static class ResultSet {
    public String Query;
}

(and then use Holder h = gson.fromJson(s, Holder.class);)

Bozho
Update my question
Yan Cheng CHEOK
@Yan Cheng CHEOK That's not what I meant. Anyway, see my update
Bozho
I have no control on the JSON string. It is returned from server.
Yan Cheng CHEOK
@Yan Cheng CHEOK see my update
Bozho
OK. I can see I miss out the Holder class.
Yan Cheng CHEOK