Map Dynamic json object to java - java

I am building a REST API with a payload that has a property called jsonContent, which holds any valid json.
{
"name":"foo",
"jsonContent":{ "abc":"My content"}
}
On the server side I want to map the it to a generic java object ,and eventually save the whole object to mongodb
private String name;
private ?????? jsonContent
I am using jackson for mapping json to java. How do I declare my java object so any json content can be used.

Use JsonNode:
private JsonNode jsonContent;

I answer my own question, Following worked just fine for me
private Map<String,Object> jsonContent;

Related

Serialization of Dynamic JSON using ProtoBuf - Java

Need some insights: How to write proto file for serializing a java POJO class containing JSONObject as attribute with Protobuf serialization.
The JSON we have is fluid (keys keep changing).
Sample:
public class POJO {
private String atr1;
private long atr2;
private Map<String, String> atr3;
private JSONObject atr4;
}
No proper apporach to handle such scenarios. However, JSON with java has fallback serialization default mechanism which is only option left with.

Bind JSON response with dynamic keys to Java object

I have a json response coming from MongoDB and in its current form I have a pojo like below to bind these month field values:-
#JsonProperty("Feb-2017")
private Float feb2017;
The problem is that these month names change with time and those values will no longer be bound to the java object.The POJO in turn is an attribute of two other objects that represent this json. I cannot change the json structure in the Db and have tried creating this pojo at runtime following this answer but I cannot figure out how to reference this object across other POJOs .
Is there any other way I could approach this problem?
Thanks.
In your POJO, add a class member as follows:
private Map<String, Object> months = new HashMap<>();
Then create a method annotated with #JsonAnySetter:
#JsonAnySetter
public void set(String key, Object value) {
months.put(key, value);
}
This method works as a fallback handler for all unrecognized properties found in the JSON document.

Using Gson how to add variable name as top level parameter for json of a REST call

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.
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.

Deserialize embeded Json fields objects into Java map

This is related to deserializing a JSON object with multiple items inside it .
I have the following Json object I need to deserialize in Java using Gson, and for the life of me, I'm pulling my hair out.
{
"Success":1,
"return":
{"MyObjects":
{"Obj1":
{"Prop1":"widgets", "Label":"Obj1", "prop2":"gadgets"}}
{"Obj2":
{"Prop1":"widgets2", "Label":"Obj2","prop2":"gadgets2"}}
{"Obj3":
{"Prop1":"widgets3", "Label":"Obj3","prop2":"gadgets3"}}
}
I have read and re-read the above linked question, and I am not quite understanding his solution.
I can make a MyJsonObject class as follows:
public class MyJasonObject{
private int success;
#SerializedName("return")
private isReturn isreturn;
}
The 'isReturn' class is where I'm lost. How should I parse the "MyObjects" into a map or a Json object? I didn't write the json string, it was handed to me... It looks like I could use a map for Myobject using the label field. But, I honestly don't know how to.

Javascript Object to Java List

I have the following type of JSON I want to send to Java (I'm using Jersey and the default JSON Parser it comes with)
{ "something" : "1", "someOtherThing" : "2" , ... }
But instead of creating an Object with all these properties in Java, I would like to have a Single HashMap (or whatever) that will allow me to still have access to the Key and the Value
Is such a thing possible?
I don't really have any code that does the transformation, I use Jersey like this
#POST
#Path("/purchase")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public StatusResult purchase(UserPurchaseRequest upr) {
}
If i put properties something and someOtherThing as Strings in my UserPurchaseRequest object, everything will come in fine, but I want to have everything in one structure (because I don't know how many values I will get, and I need their names as well)
Yes, it is possible. But still, it depends on what JSON java API you are using. For example using Jackson JSON you can create HashMap json string like this
ObjectMapper obj = new ObjectMapper();
String json = pbj.writeValue(<HashMap object>);
or vice-versa
HashMap obj = obj.readValue(json, HashMap.class);
Note - org.codehaus.jackson.map.ObjectMapper
You just need to add a Property to your Object like this
private HashMap<String,String> purchaseValues;
Jersey takes care of the rest, for some reason while you are debugging, most of the entries appear as null in the HashMap

Categories