【问题标题】:Gson custom deserialization but only one field [duplicate]Gson自定义反序列化但只有一个字段[重复]
【发布时间】:2016-11-08 10:26:09
【问题描述】:

我从 API 接收 long json,例如:

{
  "field1": "val1",
  "field2": "val2",
  ...
  "SOME_FIELD": "   ABC   ",
  ...
  "fieldx": "valx"
}

我想用 Gson 反序列化它。一切正常,但字段的“SOME_FIELD”值总是带有烦人的空格。我想 trim() 这个字段值(API 不能更改)。我知道我可以使用 JsonDeserializer 但我必须手动读取所有字段。是否可以在反序列化时只编辑一个有趣的字段,而对其余字段使用自动反序列化?

【问题讨论】:

  • This question 可能会帮助您...另一种选择是在您从对象中检索值时使用 getter。

标签: java json gson deserialization json-deserialization


【解决方案1】:

这里我正在编写一个 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();
}

}

正确阅读评论..希望你明白这个概念。

谢谢

【讨论】:

  • 感谢您的帖子,但我正在使用 Gson,将其更改为 Jackson 会花费太多时间(整个项目非常大,很多地方都使用了 gson)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多