I'm using GSON for a project. In particular I use this code to generate JSON strings:
Gson gs = new Gson();
JsonObject cmdobj = new JsonObject();
cmdobj.addProperty("cmd", cmd);
cmdobj.add("arg", args);
String cmdstr = cmdobj.toString();
which produces something like:
{"cmd":"HANDSHAKE","arg":{"protoco开发者_开发技巧l":"syncmanager","serverName":"12345678910"}}
then on a client machine this reads the json data:
String cmdstr = readCommand(this.is);
Gson gs = new Gson();
JsonObject jsobj = gs.fromJson(cmdstr, JsonObject.class);
JsonElement cmd = jsobj.get("cmd");
JsonObject args = jsobj.get("arg").getAsJsonObject();
the problem is that jsobj that should contain the parsed object doesn't contain anything ( if I do toString() prints {} ). Why this? I just want the JSonObject tree that I had on the other side, not an object serialization. Any clues?
JsonObject jsobj = new Gson().fromJson(cmdstr, JsonObject.class)
will try and build a type of JsonObject from the string - which your string clearly isn't.
I think what you want to do is get the raw parse tree - which you can do like this:
JsonObject jsobj = new JsonParser().parseString(cmdstr);
See this for more details.
精彩评论