web-dev-qa-db-fra.com

jackson Champ non reconnu

J'utilise jackson pour convertir JSON en classe Object.

JSON:

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

Classe d'objet:

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

Code:

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

Mon code lève une exception comme ça:

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

Et je ne veux pas ajouter d'accessoire à la classe Test, je veux juste que jackson convertisse la valeur existante qui existe également dans Test.

39
YETI

Jackson fournit plusieurs mécanismes différents pour configurer la gestion des éléments JSON "supplémentaires". Voici un exemple de configuration de ObjectMapper pour ne pas 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;
}

Pour d'autres approches, voir http://wiki.fasterxml.com/JacksonHowToIgnoreUnknown

80
Programmer Bruce

Depuis Jackson 2.0, l'énumération interne (DeserializationConfig.Feature) a été déplacée vers une énumération autonome (DeserializationFeature):

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

40
Owen Pauling

Si vous utilisez Jackson 2.0 (plus rapide xml)

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

Il est important de noter au préalable les changements critiques du modèle qui peuvent entraîner une rupture de la logique métier.

Pour mieux contrôler l'application, il est préférable de gérer cette exception manuellement.

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;
            }
        });

Renvoie vrai pour gérer nrecognizedPropertyException

N'ignorez pas les champs silencieusement non reconnus.

8
Flinbor