Skip to content
Advertisement

format a json of a class in spring

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

Advertisement

Answer

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

Advertisement