开发者

GSON just to read a JsonObject tree from Json data doesn't work

开发者 https://www.devze.com 2023-03-05 10:09 出处:网络
I\'m using GSON for a project. In particular I use this code to generate JSON strings: Gson gs = new Gson();

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号