I'm receiving from API long json, e.g.:
{
"field1": "val1",
"field2": "val2",
...
"SOME_FIELD": " ABC ",
...
"fieldx": "valx"
}
I would like to deserialize it with Gson. Everything works fine but field's "SOME_FIELD" value is always with annoying spaces. I would like to trim() this field value (API can't be changed). I know I can use JsonDeserializer but then I have to manually read all fields. Is it possible to edit only one interesing field while deserializing but use auto deserialization for rest of them?
Here I am writing a Demo Class to Convert JSON to a class by ignoring some of the non-used property embedded in JSON
.
Here I have used ObjectMapper
Class to deserialize the JSONObject
as an Object
.
//configuration to enables us to ignore non-used Unknow Properties.
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Test Class (Code To Convert a Json into a Class Object).
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
/**
* @param args
* @throws IOException
* @throws JsonProcessingException
* @throws JsonMappingException
* @throws JsonParseException
*/
public static void main(String[] args) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
Test o = new Test();
o.GetJsonAsObject(o.putJson());
}
//function to generate a json for demo Program.
private String putJson() throws JsonProcessingException{
HashMap<String, String> v_Obj = new HashMap<>();
v_Obj.put("field1", "Vikrant");
v_Obj.put("field2", "Kashyap");
return new ObjectMapper().writeValueAsString(v_Obj); // change the HashMap as JSONString
}
//function to Convert a json Object in Class Object for demo Program.
private void GetJsonAsObject(String value) throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Test1 obj = mapper.readValue(value, Test1.class);
System.out.println(obj);
}
}
Test1.java (Conversion POJO Class)
class Test1{
private String field1;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String toString(){
return this.field1.toString();
}
}
Read Comment Properly.. hope you got the concept .
Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With