java tutorial 傑克遜無法識別的領域




objectmapper java (4)

如果您使用的是Jackson 2.0(fasterxml)

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

我使用傑克遜將JSON轉換為對像類。

JSON:

{
    "aaa":"111",
    "bbb":"222", 
    "ccc":"333" 
}

對像類:

class Test{
    public String aaa;
    public String bbb;
}

碼:

ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(content, valueType);

我的代碼拋出像這樣的異常:

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "cccc" (Class com.isoftstone.banggo.net.result.GetGoodsInfoResult), not marked as ignorable

我不想添加一個道具類測試,我只是希望傑克遜轉換的存在值whith也存在於測試。


從Jackson 2.0開始,內部枚舉(DeserializationConfig.Feature)已經被移動到獨立枚舉(DeserializationFeature):

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


預先註意可能導致業務邏輯故障的模型的關鍵變化是重要的。

為了更好地控制應用程序,最好手動處理這個異常。

objectMapper.addHandler(new DeserializationProblemHandler() {

            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt,
                    JsonParser jp, JsonDeserializer<?> deserializer,
                    Object beanOrClass, String propertyName)
                    throws IOException, JsonProcessingException {

                String unknownField = String.format("Ignoring unknown property %s while deserializing %s", propertyName, beanOrClass);
                Log.e(getClass().getSimpleName(), unknownField);
                return true;
            }
        });

返回true以處理UnrecognizedPropertyException

不要無視默默無聞的領域。


Jackson提供了幾種不同的機制來配置“額外”JSON元素的處理。 以下是將ObjectMapper配置為不FAIL_ON_UNKNOWN_PROPERTIES

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    // { "aaa":"111", "bbb":"222", "ccc":"333" }
    String jsonInput = "{ \"aaa\":\"111\",
                          \"bbb\":\"222\",
                          \"ccc\":\"333\" }";

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,
                         Visibility.ANY);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
                     false);

    Test test = mapper.readValue(jsonInput, Test.class);
  }
}

class Test
{
  String aaa;
  String bbb;
}

有關其他方法,請參閱http://wiki.fasterxml.com/JacksonHowToIgnoreUnknown





jackson