Gson自定义反序列化,但只有一个领域

use*_*048 5 java json gson deserialization json-deserialization

我从API长的json接收,例如:

{
  "field1": "val1",
  "field2": "val2",
  ...
  "SOME_FIELD": "   ABC   ",
  ...
  "fieldx": "valx"
}
Run Code Online (Sandbox Code Playgroud)

我想和Gson反序列化。一切正常,但字段的“ SOME_FIELD”值始终带有烦人的空格。我想trim()此字段值(无法更改API)。我知道我可以使用JsonDeserializer,但随后我必须手动读取所有字段。反序列化时是否只能编辑一个内部字段,而其余部分使用自动反序列化?

Vik*_*yap 1

这里我正在编写一个演示类,通过忽略嵌入在JSON.

在这里,我使用ObjectMapperClass 将其JSONObject反序列化为Object.

 //configuration to enables us to ignore non-used Unknow Properties.
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Run Code Online (Sandbox Code Playgroud)

测试类(将 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

}

正确阅读评论……希望您明白了。

谢谢