简体   繁体   中英

Gson to json string conversion

Hello all I am setting value to an object and then running gson.tojson(myObject)

This works fine and the output looks like:

{"val1":22,"val2":4,"val3":34,"val4":1046.0,"val5":"hello","val6":true}

However I now need my json string to look like

{"myJson":  {"val1":22,"val2":4,"val3":34,"val4":1046.0,"val5":"hello","val6":true}}

is there a built in way to do this or should I just do sting concat?

Yes, you just need to get the JsonTree and add an inner object to it

JsonElement innerObject = gson.toJsonTree(myObject);
JsonObject outerObject = new JsonObject();
outerObject.add("myJson",innerObject);

Now, outerObject has innerObject so you can take it from there, convert it to String if you want.

String json = outerObject.toString();

I don't know if there is a option for that with Gson but you can create a wrapper class for your object :

class ObjectWrapper {
    Object myJsonObject;
}

And use gson.toJson() on the wrapped object.

You can create a wrapper class which has your object set in its property "myJson".

public class Wrapper {
  <Yourclass> myJson;

  public Wrapper(<Yourclass> obj){
    myJson = obj;
  }
}

Afterwards create the JSON based on the Wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM