format a json of a class in spring - java

I am new with spring and I want the json response of my class
public class Mapping { public String name; public Object value; }
be changed from
{"name" : 'value of field name', "value": 'value of field value'}
to
{'value of field name' : 'value of field value'}
I tried #JsonValue and #JsonKey but they didn`t work. how can I do this.
edit:
I want to set the value of key dynamically and based on value of the field name.
edit_P2:
this class, is a model for a single field in json, means an object of it must hold one key and value of my json, like a map, it has key and values, and what i want is to store key in field 'name' and the value in outher field, so when i return this object, it returns the string in field 'name' as key and the other one as value, lets assume name="the key" and value="the value", i want it to be return as "the key":"the value".

Edited in reaction to your comment:
Have your class changed from
public class Mapping {
public String name;
public Object value;
}
to simply this:
public class Mapping {
public String name;
}
and in your code to this:
Mapping myMapping = new Mapping();
myMapping.name = "myValue";
This will be parsed to JSON: {"name":"myValue"}
Additional edit
OK, I think I understood what you want and I think it might be impossible in a single json serialization. Your options would be to create a custom serializer See this article: Jackson – Custom Serializer. Or (in my opinion simpler way) add a method to your class toMap() that will produce your desired map and than convert that map to Json. That will give you desired Json. BTW for simple Json serializer/deserializer that is a wrapper over Json-Jackson library look here: JsonUtils. The library could be found as Maven artifact and on Github (including source code and Javadoc).
Original answer:
You need to use annotation #JsonProperty and its attribute "name". Here is a good article about it: Jackson – Change Name of Field

Related

How does gson maps JSON keys with the fields in Java classes while deserializing the JSON

I am searching for this for quite some time now but still, it is not clear to me. I have a JSON file which looks like this:
{
"Name" : "Foo Bar",
"Grade" : "Some Grade",
"Org" : "Some Org"
}
For deserializing this JSON (using gson) I have created a Java class called StudentDetails.java which looks like this:
public class StudentDetails
{
public String name;
public String grade;
public String org;
}
Now I have a couple of questions regarding this:
Will gson automatically maps the fields in StudentDetails.java with corresponding keys even if the fields start with lower case and keys start from upper case in the JSON file. I have looked for #SerializedName but my code works without even using it. On the contrary if I am using something like #SerializedName("Name) with name field, it's getting assigned to null after deserialization. I am so confused right now.
Will deserialization work without even getter and setter methods? In jackson you write setter and getter methods.
If above is true, does it work even in the case of private fields?
I'm note sure about this one but i think the case only matters after the first character because you normally don't start the name of field with an upper-case character.
Yes GSON will automatically map the fields.
Yes GSON does not need getter/setter
(https://stackoverflow.com/a/6203975/4622620)
Yes GSON can handle private fields because it uses reflections (https://stackoverflow.com/a/28927525/4622620)

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.

Unable to deserialize alternate name with GSON, AutoValue, and Retrofit 2

I am using retrofit version 2.1.0 to deserialize JSON into pojos. A field in the pojo can be received under different names in the json. To deserialize the field correctly, I used the #serializedName annotation in the following way:
#AutoValue
public abstract class Media implements Parcelable {
#SerializedName(value = "title", alternate = {"name"})
public abstract String title();
// More fields and code
However, for some reason, when the resulting JSON has the field under the key "title", Gson reads it correctly, but when the field is associated with the "name" key, it does not get read.
How can I get GSON to recognize the alternate name during deserialization?
I'm assuming you're using the com.ryanharter.auto.value:auto-value-gson plugin. Support for alternate serialized names was not added until version 0.4.0. Update to com.ryanharter.auto.value:auto-value-gson:0.4.2 and you should then be able to deserialize alternate names.
Seem the problem is related to Parcel.
You might want take a look at this
parceler
#AutoValue
#Parcel
public abstract class Media {
#ParcelProperty("title") public abstract String title();
}

Design Java class for Jackson when JSON key has no one name but different values

How to model in Java (for Jackson library) following json file where the key is the file name so it has no (constant) name
{
"core/core-rwd/src/scss/_colors.scss": [
{
"line": 1,
"column": 13,
},
I would like to have something like
class MySet {
???? files;
}
class File {
int line;
int column;
}
What should I replace ??? with to make this compatible with Jackson?
Assuming that name is dynamic, you won't be able to map it to a POJO type field.
The solution is to deserialize the JSON to a Map<String, Something[]>. The Map's values can still be some known type if they do map to a POJO type.
Alternatively, you can use Jackson's ObjectNode, a Map-like data structure with methods that make sense in a JSON context.

Is there a way to modify a POJO field and return the POJO

Is there a way to modify the field of POJO with new property(like using MixIns or #JSONProperty) and get the modified POJO back ? (A way to add/modify field of a POJO dynamically ?)
Like I have a class
class PojoA<T>{
private T data;//field to be modified as NewData
}
So, I tried with MixIns like
public interface PojoMixIn<T> {
#JsonProperty("NewData")
T getData();
}
Now to get the modified field, I use ObjectMapper
mapper.addMixInAnnotations(PojoA.class,PojoMixIn.class);
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojoA);
The actual result is a String, but can I be able to get the modified POJO?

Categories