4

I am trying call a REST service and using gson I am getting the following json for the following java pojo.

pojo

public class AlphaParameters {
private  int one;
private int two;
private int three;

//getter setters
//constructors
}

Json

{"one":4,
"two":5,
"three":10
}

I am using the following code

Gson gson = new Gson()
AlphaParameters alphaParameters = new AlphaParameters(one,two,three);
gson.toJson(alphaParameters );

Earlier this code used to work, but now seems the server side which is on .net changed their implementation and now they are expecting the json in the following format. Everything is same but seems now they want the toplevel variable name in the json.

{"alphaParameters":
    {"one":4,
    "two":5,
    "three":10
    }
}

Question : Is there a specific api of Gson which I can use to generate the above json without refactoring my code ? Or writing a wrapper class to include alphaParameters will be a better approach . ( I will have to write a lot of boilerplate code for latter ).

Thanks for your help.

2
  • You could put the AlphaParameters instance in a map, under an "alphaParameters" key, just before serialization. Is this possible in your case? It might also be possible to change the behaviour of the Gson by obtaining it from a properly configured GsonBuilder but I'm not sure about this part. May 20, 2014 at 5:02
  • I googled for GsonBuilder settings , but no luck so far :(
    – Shakti
    May 20, 2014 at 5:08

1 Answer 1

3

I don't think Gson itself allows this kind of serialization but there is a number of ways you could tackle this problem without creating wrapper classes.

In my comment, I suggested putting the object in a map but that's a bit strange and you can do it so it looks more obvious in the code and probably performs better.

public Gson wrapJson(Object objectToSerialize) {
  Gson gson = new Gson();
  JsonObject result = new JsonObject();
  //Obtain a serialized version of your object
  JsonElement jsonElement = gson.toJsonTree(objectToSerialize);
  result.add(objectToSerialize.getClass().getSimpleName(), jsonElement);
  return result;
}

Then you can use it like this:

AlphaParameters alphaParameters = new AlphaParameters(one,two,three);
wrapJson(alphaParameters);

This allows you to use one pretty universal method in every case like this without writing boilerplate classes.

I used the class name to generate the key but feel free to modify this as it suits you. You could pass the key name as a parameter to make this wrapper utility more flexible.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.