Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - converting java object to json - Need all key keys to upper case

Need your help on conversion of java objects to json. current the json result showing all the key in small letter case, i need it to be upper case.

ObjectMapper mapper = new ObjectMapper();
Writer strWriter = new StringWriter();
mapper.writeValue(strWriter, obj);
String jsonString= strWriter.toString();

and the result is

[{"flags":"1","name":"Peter","location":"London","startDate":"2012-01-06 00:00"}]

but i want results like this (all key key value should be in UPPER CASE):

[{"FLAGS":"YU","NAME":"Peter","LOCATION":"London","STARTDATE":"2012-01-06 00:00"}]

and also is it possible to get like this also (key first letter in upper case):

[{"Flags":"1","Name":"Peter","Location":"London","StartDate":"2012-01-06 00:00"}]

Can anyone help me on this.

Thanks in advance.

like image 273
Asif Avatar asked Jun 15 '12 10:06

Asif


1 Answers

There are multiple ways to do it with Jackson.

Annotations

You could annotate your object with @JsonProperty annotations on your fields or on your getter methods.

Example:

@JsonProperty("Name")
public final String name;

@JsonProperty("Location")
public String getLocation() {
  return location;
}

Implement JsonSerializableWithType interface

@Override
public void serialize(final JsonGenerator jG, final SerializerProvider p)
    throws IOException, JsonProcessingException
{
    serializeWithType(jG, p, null);
}

@Override
public void serializeWithType(final JsonGenerator jG, final SerializerProvider p, final TypeSerializer typeSer)
    throws IOException, JsonProcessingException
{
    // here you can do your own serialization
}
like image 73
KARASZI István Avatar answered Oct 18 '22 16:10

KARASZI István