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?
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:
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.
queryrather thanQuery)Update If you really can’t change the json input, you can mirror the structure this way:
(and then use
Holder h = gson.fromJson(s, Holder.class);)