java - Gson custom deserialization but only one field -
this question has answer here:
i'm receiving api long json, e.g.:
{ "field1": "val1", "field2": "val2", ... "some_field": " abc ", ... "fieldx": "valx" }
i deserialize gson. works fine field's "some_field" value annoying spaces. trim() field value (api can't changed). know can use jsondeserializer have manually read fields. possible edit 1 interesing field while deserializing use auto deserialization rest of them?
here writing demo class convert json class ignoring of non-used property embedded in json
.
here have used objectmapper
class deserialize jsonobject
object
.
//configuration enables ignore non-used unknow properties. mapper.configure(deserializationfeature.fail_on_unknown_properties, false);
test class (code convert json 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 generate json 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 hashmap jsonstring } //function convert json object in class object 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 got concept .
thanks
Comments
Post a Comment