这里我正在编写一个 Demo Class,通过忽略 JSON 中嵌入的一些未使用的属性来将 JSON 转换为一个类。
这里我使用ObjectMapper 类将JSONObject 反序列化为Object。
//configuration to enables us to ignore non-used Unknow Properties.
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
测试类(将 Json 转换为类对象的代码)。
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(转换POJO类)
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();
}
}
正确阅读评论..希望你明白这个概念。
谢谢