Mined and Summarized Use Cases For API: com.fasterxml.jackson

  1. How to (De)serialize field from object based on annotation using Jackson?

    I used the JsonProperty annotation instead of wrapping the functionality in the ContextualSerializer because it seemed silly to reinvent the wheel. Finally the method that performs the serialization just creates an additional ObjectMapper and registers a module in the original ObjectMapper. .. details

    1. import java.util.*
    2. import com.fasterxml.jackson.annotation.*
    3. public class Resource extends BaseResource{ private String name
    4. @JsonProperty("sub_resource_id") @JsonId private SubResource subResource
    5. @JsonProperty("sub_resource_ids") @JsonId private List<SubResource> subResources
    6. //getters and setters public String getName() {return name
    7. } public void setName(String name) {this.name = name
    8. } public SubResource getSubResource() {return subResource
    9. } public void setSubResource(SubResource subResource) {this.subResource = subResource
    10. } public List<SubResource> getSubResources() {return subResources
    11. } public void setSubResources(List<SubResource> subResources) {this.subResources = subResources
    12. }}

    Positive Reactions
    1. If so then could you please accept it?
    Other Reactions
    1. Did this answer the question?
    2. If not then what didn't it answer?

    • See Also (2)
    1. How do I marshall nested key,value pairs into JSON with Camel and Jackson library?

      One way to represent this is What you'll end up with is this which although represents the data is far from ideal To get what you want use JsonAnyGetter. Something like this it could be made much easier to use) which produces I've been battling this today and your question inspired me to make it bloody work D The annotations are here annotations/wiki/Jackson-Annotations annotations/wiki/Jackson-Annotations See JUnit test here . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class Whatever {
      2. Map<String, String> keyvalues = new TreeMap<String, String>()
      3. @JsonProperty Map<String, String> visibility = new TreeMap<String, String>()
      4. @JsonAnyGetter
      5. public Map<String, String> getKeyvalues() {
      6. return keyvalues
      7. }
      8. }

      Positive Reactions
      1. I'm also using com.fasterxml.jackson.dataformat jackson-dataformat-csv 2.2.3 which seems to be importing it as well.
      2. well I hope it works for you.
      3. Thanks for the info.
      4. Please mark the answer as accepted :).
      5. Tom, thank you for the information.
      6. This test works for me.
      7. Thanks.
      Negative Reactions
      1. I discovered some Jackson library conflicts in my pom.xml that I'm cleaning up.
      Other Reactions
      1. I guess that's why its using an older version.
      2. Are you specifying that newer version in your pom.xml or your applicationContext.xml?
      3. What version Jackson are you using?
      4. I couldn't seem to get maven to pull down the fasterxml.jackson.library, so I downloaded the jackson-annotations-2.2.3.jar and added it to my classpath.
      5. Can you post your pom.xml and Camel applicationContext.xml files with your JUnit test?
      6. It now points my SensorGenerator class to the same library as yours, but I still don't get the nested visibility.
      7. Mine is imported as a dependency of restlet 2.2-M3.
      8. I added in the code you suggested, but when I run the program I only see the keyvalues in the JSON.
      9. URL_https://gist.github.com/TomDemeranville/7009250 .
      10. I looked in both and I don't seem to specify a version for the Jackson library.
      11. Btw, I looked under my .classpath under my Eclipse project and found out that yes, I am specifying multiple versions of the Jackson library, i.e.
      12. Part of my jackson is 2.1, other parts 2.2.3.
      13. I want to see if I can figure out what to add to call the newer Jackson library.
      14. here it is as a JUnit test.
      15. Here's all I've currently specified in my applicationContext.xml for marshalling to JSON: .
      16. I'm using camel-jackson 2.12.1.
      17. For some reason I don't see the nested visibility fields.
      18. I'll attach my SensorGenerator.java class, perhaps I'm missing something :-).
      19. You may have both versions on your classpath.
      20. I'm using Jackson 2.2.3 I think.
      21. Doh.
      22. The new version uses the fasterxml namespace.
      23. You are using an old version.
      24. And then further down in my .classpath I have: with a bunch of attributes set.
      25. You are using: import com.fasterxml.jackson.annotation.JsonAnyGetter;import com.fasterxml.jackson.annotation.JsonProperty; and I'm using import org.codehaus.jackson.annotate.JsonAnyGetter;import org.codehaus.jackson.annotate.JsonProperty; Did you specify the com.fasterxml library in your pom.xml?
      26. I have the following dependency in my pom.xml: org.apache.camel camel-jackson ${camel} where I define ${camel} above as 2.12.1.
      27. : .
      28. I just noticed that I'm using different libraries that you are for JsonAnyGetter and JsonProperty.

    2. Jackson API: partially update a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class KnownPart { @JsonProperty private Customer customer
      2. @JsonProperty private BrowserInfo browser
      3. } private static class Customer { @JsonProperty private int id
      4. @JsonProperty private String name
      5. @JsonProperty private Address[] addresses
      6. // just to make it more complex for this example public Customer(int id, String name, Address[] addresses) { this.id = id
      7. this.name = name
      8. this.addresses = addresses
      9. } public Customer() { } } private static class Address { @JsonProperty private String street
      10. @JsonProperty private String city
      11. public Address(String street, String city) { this.street = street
      12. this.city = city
      13. } public Address() { } } private static class BrowserInfo { @JsonProperty private String agent
      14. @JsonProperty private String version
      15. public BrowserInfo(String agent, String version) { this.agent = agent
      16. this.version = version
      17. } public BrowserInfo() { } }

  2. How to (De)serialize field from object based on annotation using Jackson?

    Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. .. details

    1. import com.fasterxml.jackson.core.*
    2. import com.fasterxml.jackson.databind.*
    3. import com.fasterxml.jackson.databind.ser.*
    4. import java.io.*
    5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
    6. implements ContextualSerializer /*<BaseResource>*/ {
    7. private ObjectMapper mapper
    8. private boolean useJsonId
    9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
    10. this(mapper, false)
    11. }
    12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
    13. this.mapper = mapper
    14. this.useJsonId = useJsonId
    15. }
    16. @Override
    17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
    18. throws IOException {
    19. if (useJsonId) {
    20. jgen.writeString(br.getId().toString())
    21. } else {
    22. mapper.writeValue(jgen, br)
    23. }
    24. }
    25. @Override
    26. public JsonSerializer<BaseResource> createContextual(
    27. SerializerProvider config, BeanProperty property)
    28. throws
    29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
    30. if (null == property) {
    31. return new ContextualJsonIdSerializer(mapper, false)
    32. }
    33. JsonId ann = property.getAnnotation(JsonId.class)
    34. if (ann
    35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
    36. }
    37. if (ann == null) { //|| ann.length() == 0) { return this
    38. //new ContextualJsonIdSerializer(false)
    39. }
    40. return new ContextualJsonIdSerializer(mapper, true)
    41. }
    42. }

    Positive Reactions
    1. If so then could you please accept it?
    Other Reactions
    1. Did this answer the question?
    2. If not then what didn't it answer?

  3. Removing a node in json in Java

    obsessiveCookie You're welcome and good luck!. This solution uses pure Jackson by setting the rootName on the ObjectReader . .. details

    1. import com.fasterxml.jackson.core.JsonProcessingException
    2. import com.fasterxml.jackson.databind.ObjectMapper
    3. import com.fasterxml.jackson.databind.ObjectReader
    4. import java.io.IOException
    5. public class User {
    6. public static void main(String[] args) throws JsonProcessingException, IOException {
    7. String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}"
    8. ObjectMapper mapper = new ObjectMapper()
    9. ObjectReader reader = mapper.reader(User.class).withRootName("User")
    10. User user = reader.readValue(json)
    11. System.out.println(user.getFirstname())
    12. }
    13. private String firstname
    14. private String lastname
    15. private String verified
    16. private String gender
    17. public String getFirstname() {
    18. return firstname
    19. }
    20. public void setFirstname(String firstname) {
    21. this.firstname = firstname
    22. }
    23. public String getLastname() {
    24. return lastname
    25. }
    26. public void setLastname(String lastname) {
    27. this.lastname = lastname
    28. }
    29. public String getVerified() {
    30. return verified
    31. }
    32. public void setVerified(String verified) {
    33. this.verified = verified
    34. }
    35. public String getGender() {
    36. return gender
    37. }
    38. public void setGender(String gender) {
    39. this.gender = gender
    40. }
    41. }

    Other Reactions
    1. +1 Was not aware of this alternative with jackson.

  4. Pretty print JSON output in JBoss RESTful service

    I have a bit of a round about solution that prints it pretty decently. Not the best Pretty Print but it is enough You'll need the following from Maven Then you can change your method to something like this Since what it does is 1. .. details

    1. import org.codehaus.jackson.JsonGenerationException
    2. import org.codehaus.jackson.map.JsonMappingException
    3. import org.codehaus.jackson.map.ObjectMapper
    4. import org.codehaus.jackson.map.ObjectWriter
    5. ...private final ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter()
    6. ...@GET@Path("books")@Produces({ MediaType.APPLICATION_JSON })public Response getBooks() { return Response.status(Status.OK).entity(WRITER.writeValueAsString(doGetBooks())).build()
    7. }

    • See Also (1)
    1. Jackson Library JSON Mapper to String

      Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import java.io.IOException
      2. import java.util.List
      3. import org.codehaus.jackson.JsonGenerationException
      4. import org.codehaus.jackson.map.JsonMappingException
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class A {
      7. private List<B> b
      8. private int c
      9. public List<B> getB() {
      10. return b
      11. }
      12. public void setB(List<B> b) {
      13. this.b = b
      14. }
      15. public int getC() {
      16. return c
      17. }
      18. public void setC(int c) {
      19. this.c = c
      20. }
      21. public static void main(String[] args)
      22. throws JsonGenerationException, JsonMappingException, IOException {
      23. A a = new A()
      24. ObjectMapper mapper = new ObjectMapper()
      25. String temp = mapper.writeValueAsString(a)
      26. System.out.println(temp)
      27. }
      28. }
      29. class B {}

      Positive Reactions
      1. The method read works only if the List** b is empty..**
      2. I have change something in my Class A and the method save go.
      3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
      Negative Reactions
      1. Now i have another problem..
      Other Reactions
      1. I have substitute List** b new List**() with List** new ArrayList**().
      2. Are you using Eclipse?
      3. Meaning you do not have the appropriate jar file in your classpath.
      4. Why??
      5. The same function called in two activities..********
      6. See updated answer.
      7. If you copied my complete example and it did not run, then its a build path issue.
      8. Also, make sure you have get/set methods for each field in Class B.
      9. @user2520969 Did the example help?

  5. How to deserialize dynamic JSON fields with Jackson?

    None .. details

    1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
    2. // import com.fasterxml.jackson.databind.ObjectMapper
    3. import org.codehaus.jackson.annotate.JsonTypeInfo
    4. import org.codehaus.jackson.map.ObjectMapper
    5. import javax.ws.rs.ext.ContextResolver
    6. import javax.ws.rs.ext.Provider
    7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
    8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
    9. this.defaultObjectMapper = new ObjectMapper()
    10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
    11. // .enableDefaultTyping()
    12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
    13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
    14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
    15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
    16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
    17. return this.defaultObjectMapper
    18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    • See Also (1)
    1. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the second problem. If instead the goal is to deserialize to a subclass type without a JSON element specifically dedicated to indicate what the subclass type is then that is also possible so long as something in the JSON can be used to decide what the subclass type should be. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import org.codehaus.jackson.annotate.JsonSubTypes
      2. import org.codehaus.jackson.annotate.JsonSubTypes.Type
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      6. A a = new A()
      7. B b = new B()
      8. C c = new C()
      9. ObjectMapper mapper = new ObjectMapper()
      10. String baseJson = mapper.writeValueAsString(base)
      11. System.out.println(baseJson)
      12. // {"type":"BaseClass","baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      13. System.out.println(aJson)
      14. // {"type":"a","baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      15. System.out.println(bJson)
      16. // {"type":"b","baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      17. System.out.println(cJson)
      18. // {"type":"c","baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      19. System.out.println(baseCopy)
      20. // baseName: base name BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      21. System.out.println(aCopy)
      22. // baseName: base name, aName: a name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      23. System.out.println(bCopy)
      24. // baseName: base name, bName: b name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      25. System.out.println(cCopy)
      26. // baseName: base name, cName: c name }}@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = A.class, name = "a"), @Type(value = B.class, name = "b"), @Type(value = C.class, name = "c") }) class BaseClass{ public String baseName = "base name"
      27. @Override public String toString() {return "baseName: " + baseName
      28. }}class A extends BaseClass{ public String aName = "a name"
      29. @Override public String toString() {return super.toString() + ", aName: " + aName
      30. }}class B extends BaseClass{ public String bName = "b name"
      31. @Override public String toString() {return super.toString() + ", bName: " + bName
      32. }}class C extends BaseClass{ public String cName = "c name"
      33. @Override public String toString() {return super.toString() + ", cName: " + cName
      34. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

  6. How do I parse JSON into a Map with lowercase keys using Jackson?

    Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. .. details

    1. import org.codehaus.jackson.map.KeyDeserializer
    2. import org.codehaus.jackson.map.ObjectMapper
    3. import org.codehaus.jackson.map.module.SimpleModule
    4. import org.codehaus.jackson.Version
    5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
    6. }}// ...ObjectMapper mapper = new ObjectMapper()
    7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
    8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
    9. mapper.registerModule(module)
    10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

  7. Jackson with JSON: Unrecognized field, not marked as ignorable

    None .. details

    1. @JsonIgnoreProperties(ignoreUnknown = true)

    • See Also (2)
    1. Deserialize json with different object types

      Your class should be deserialized automatically if you modify it like this Note. Jackson 2.1 required**) Then to deserialize in your code . details

      Reactions - Positive 11, Negative 3, Others 0

      1. @JsonIgnoreProperties("team_id")@JsonNamingStrategy(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy)public class Registration implements Serializable { private static final long serialVersionUID = 1L
      2. private int id
      3. private String currentStatus
      4. private Date expirationTime
      5. @JsonIgnore private Volunteer volunteer
      6. @JsonIgnore private Team team
      7. public Registration() { } // other code}

      Positive Reactions
      1. Awesome it works!
      2. The result: succes is only meant to check if the user is signed in and if the input was correct (the response results from scanning a QR code).
      3. Well, no, it is not necessary.
      4. Jackson:1.9.12 I really appreciate your help :).
      5. Sounds strange to serialize Registration in SuccessfulOperation to me.
      6. and updated to Jackson 2.2.2 Thanks!
      7. Thanks for your quick answer!
      8. It is just the cleanest solution I know when dealing with "polymorphic JSON" ;) You still did not show what your Registration class looks like.
      9. The most recent version is 2.2.1!
      10. And good choice on Jackson... Android's JSON library is poor, to be honest.
      11. Hestitated to try GSon but Jackson is doing great :).
      Negative Reactions
      1. No problem!
      2. Argh, 1.9.12???
      3. I'm sorry, I added it as edit now.
      Other Reactions
      1. !.
      2. Is it really necessary to create those two subclasses?
      3. OK, hold on, I'll edit my answer with a fully annotated class; what Jackson version are you using?
      4. Upgrade :p My code will work with 2.1.x (edited), but I doubt it will with 1.9.12...
      5. I used jackson before in college when creating a java webapp.

    2. Jackson with JSON: Unrecognized field, not marked as ignorable

      I found this useful to avoid creating a wrapper class Map dummy<String,Student myClientResponse.getEntity(new GenericType<Map<String Student>>(){}) and then Student myStudent dummy.get("wrapper"). You can use Jackson's annotation. details

      Reactions - Positive 6, Negative 0, Others 0

      1. @JsonIgnoreProperties

      Positive Reactions
      1. great answer !.
      2. youse rockses!
      3. thank you :).
      4. i must add that you do need the (ignoreUnknown true) when annotating your class otherwise it won't work.
      5. In one view, I'd like to serialize with a certain set of fields.
      6. thanks !
      Other Reactions
      1. Ariel, is there any way to declare this external to the class?
      2. I haven't done it but I believe that you can get somewhere in the annotations processing code and add the behavior programatically, although I can't think why you would like to do it.
      3. Why this answer is not accepted yet?
      4. In another view, I want a different set of fields serialized (or perhaps rename the properties in the JSON).
      5. Can you give me an example?
      6. I'm serializing classes that I do not own (cannot modify).

  8. Jackson API: partially update a string

    None .. details

    1. @Override public String getModuleName() { return "MyModule"
    2. } @Override public Version version() { return new Version(0, 0, 1, "SNAPSHOT")
    3. } @Override public void setupModule(Module.SetupContext context) { context.addBeanSerializerModifier(new org.codehaus.jackson.map.ser.BeanSerializerModifier() { private UnknownPartSerializer cs
    4. @Override public JsonSerializer modifySerializer(SerializationConfig config, BasicBeanDescription beanDesc, JsonSerializer<?> serializer) { return UnknownPart.class.isAssignableFrom(beanDesc.getBeanClass()) ? new UnknownPartSerializer((BeanSerializerBase) serializer) : serializer
    5. } })
    6. } }

  9. Jackson API: partially update a string

    The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . .. details

    1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
    2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
    3. jgen.writeStartObject()
    4. serializeFields(up, jgen, provider)
    5. jgen.writeEndObject()
    6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
    7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
    8. } else { props = _props
    9. } int i = 0
    10. try { for (final int len = props.length
    11. i < len
    12. ++i) { BeanPropertyWriter prop = props[i]
    13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
    14. bean.tree.remove(prop.getName())
    15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
    16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
    17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
    18. jgen.writeFieldName(e.getKey())
    19. jgen.writeObject(e.getValue())
    20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
    21. wrapAndThrow(provider, e, bean, name)
    22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
    23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
    24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
    25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
    26. throw mapE
    27. } } }

  10. Convert JSON from URL to JSONNode

    Thanks again. I see no reason why you'd need to use a Map<String Object when Jackson has the almighty JsonNode See the databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html javadoc for-JsonNode . .. details

    1. final JsonNode node = new ObjectMapper().readTree(new URL("yourURLHere")

    Positive Reactions
    1. I will update them later, and hope that that solves the issue.
    2. OK, compiled successfully, many thanks.
    3. Update to the latest (2.2.x) ;).
    4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
    5. Please show the dependencies you have.
    Negative Reactions
    1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
    Other Reactions
    1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
    2. I changed it to:.
    3. There you are, as you can see some them are older than that.
    4. It does work; if it doesn't, it means you use an old version of jackson- databind.
    5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
    6. I've now altered the code.

    • See Also (1)
    1. Getting both JSONObject and Google Gson feature in a single library

      You can use Jackson . It has a databinding solution like Gson and a tree-model-view like JSONObject . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Main {
      4. public static class Me {
      5. public String key
      6. }
      7. public static void main(String[] args) throws IOException {
      8. ObjectMapper mapper = new ObjectMapper()
      9. String json = "{\"key\" : \"value\"}"
      10. // Feature 1 JsonNode rootNode = mapper.readValue(json, JsonNode.class)
      11. System.out.println(rootNode.get("key").getTextValue())
      12. // Feature 2 Me value = mapper.readValue(json, Me.class)
      13. System.out.println(value.key)
      14. }
      15. }

      Positive Reactions
      1. I am very happy with it :).
      2. Thanks for recommending this library.
      3. It does support sub elements.
      4. Map userData mapper.readValue(json, Map.class); it's considered as simple databinding.
      Negative Reactions
      1. Hum my bad, it seems to work with Map, List and String arrays.
      Other Reactions
      1. But...but...but... URL_http://pastebin.com/CRUH4dyG I try.
      2. No, not really, as JSon elements can have other sub elements, the JsonNode system is way better.
      3. May I know which method is better?
      4. For feature 1, is it OK for me to HashMap untyped mapper.readValue(json, HashMap.class);.
      5. Is that what you mean?

  11. Convert JSON from URL to JSONNode

    See methods etc etc. shameless plug And if you want to use JSON-Pointer to navigate your JSON coreutils you-can-also-do-that . .. details

    1. final JsonPointer ptr = JsonPointer.of("current_observation", "display_location")
    2. final JsonNode displayLocation = ptr.get(node)

    Positive Reactions
    1. I will update them later, and hope that that solves the issue.
    2. OK, compiled successfully, many thanks.
    3. Update to the latest (2.2.x) ;).
    4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
    5. Please show the dependencies you have.
    Negative Reactions
    1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
    Other Reactions
    1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
    2. I changed it to:.
    3. There you are, as you can see some them are older than that.
    4. It does work; if it doesn't, it means you use an old version of jackson- databind.
    5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
    6. I've now altered the code.

  12. Flatten JSON into Specific Format

    After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . .. details

    1. import java.io.File
    2. public class JacksonProgram {
    3. public static void main(String[] args) throws Exception {
    4. JsonConverter converter = new JsonConverter()
    5. String result = converter.convert(new File("/tmp/source.json"))
    6. System.out.println(result)
    7. }
    8. }

    • See Also (1)
    1. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

  13. How to use JSONDeserializer to deserialize this string?

    None .. details

    1. public void readValueAsMap() throws Exception{ String value = "{\"226167\":\"myshow\",\"3193\":\"yourshow\"}"
    2. ObjectMapper mapper = new ObjectMapper()
    3. Map<String,String> valueAsMap = mapper.readValue(value, Map.class)
    4. Collection<String> values = valueAsMap.keySet()
    5. assertTrue(values.contains("226167"))
    6. assertTrue(values.contains("3193"))
    7. }

    • See Also (3)
    1. Deserialize JSON with Jackson without proper field

      Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. Example with MessageWrapper . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      5. ObjectMapper mapper = new ObjectMapper()
      6. Message message = mapper.readValue(inputJson, Message.class)
      7. System.out.println(mapper.writeValueAsString(message))
      8. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      9. public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      10. } public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      11. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

    2. Simplest method to Convert Json to Xml

      For a simple solution I recommend Jackson as it can transform arbitrarily complex JSON into XML with just a few simple lines of code. This demo uses Jackson-1.7.7 the newer 1.7.8 should also work) xml-databind/wiki Jackson-XML-Databind-0.5.3 not yet compatible with Jackson 1.8) and Stax2-3.1.1 . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.ObjectMapper
      2. import com.fasterxml.jackson.xml.XmlMapper
      3. public class Foo{ public String name
      4. public Bar bar
      5. public static void main(String[] args) throws Exception { // JSON input: {"name":"FOO","bar":{"id":42}} String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}"
      6. ObjectMapper jsonMapper = new ObjectMapper()
      7. Foo foo = jsonMapper.readValue(jsonInput, Foo.class)
      8. XmlMapper xmlMapper = new XmlMapper()
      9. System.out.println(xmlMapper.writeValueAsString(foo))
      10. // <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo> }}class Bar{ public int id
      11. }

    3. Setting up JSON custom deserializer

      Is there a way to tell Jackson to always use the custom deserializer to deserialize Long without having to use JsonDeserialize(using=LongJsonDeserializer.class annotation each time. Here's a full demo application. details

      Reactions - Positive 2, Negative 0, Others 0

      1. LongJsonDeserializer deserializer = new LongJsonDeserializer()
      2. SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      3. module.addDeserializer(Long.class, deserializer)
      4. ObjectMapper mapper = new ObjectMapper()
      5. mapper.registerModule(module)

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

  14. Mapping JSON data to Java objects

    None .. details

    1. import java.io.File
    2. import java.net.*
    3. import org.codehaus.jackson.map.ObjectMapper
    4. public class Movie {
    5. public static void main(String[] args) throws Exception {
    6. MovieResponse response
    7. ObjectMapper mapper = new ObjectMapper()
    8. response = mapper.readValue(new File("C:\\M.json"), MovieResponse.class)
    9. System.out.println(response)
    10. }
    11. }

  15. Jackson deserializing nested polymorphic type

    Here is a code that works but I am not sure if it answers right to all the subtypes stuff. Remove the annotations from the other classes and it should work just tested it). .. details

    1. @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
    2. public abstract static class FirstLevel {
    3. public abstract String getTestValue()
    4. }

    • See Also (1)
    1. Generic JSON object conversion

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.annotate.JsonTypeInfo
      2. @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
      3. public abstract class Message {
      4. protected Message() {}
      5. }

  16. How do I serialize an associated object differently using Jackson and annotations?

    Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. .. details

    1. public static class CustomFilter extends SimpleBeanPropertyFilter {
    2. private Class<?>[] _nextViews
    3. public void setNextViews(Class<?>[] clazz) {
    4. _nextViews = clazz
    5. }
    6. @Override
    7. public void serializeAsField(
    8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
    9. throws Exception {
    10. Class<?>[] propViews = writer.getViews()
    11. if (propViews != null && _nextViews != null) {
    12. for (Class<?> propView : propViews) {
    13. System.out.println(propView.getName())
    14. for (Class<?> currentView : _nextViews) {
    15. if (!propView.isAssignableFrom(
    16. currentView)) { // Do the filtering! return
    17. }
    18. }
    19. }
    20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
    21. }
    22. }

    Positive Reactions
    1. I think it can give a thread safe and much simpler implementation.
    2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
    3. I'll end up doing something like your example, just with some tweaks.
    4. if it not a problem, please, do the refactoring with a multithreading.
    5. However, my solution is still useful if you have a lot of properties to filter.
    6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
    7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
    Negative Reactions
    1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
    Other Reactions
    1. I have some refactoring to do now...
    2. I ended up looking at BeanSerializerModifier.class.
    3. I will look at it tomorrow morning.
    4. I had already seen that but didn't have time and forgot.
    5. @RansomBriggs Hmm, I agree.

  17. How do I serialize an associated object differently using Jackson and annotations?

    The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . .. details

    1. public class CustomSerializer extends JsonSerializer<Object> {
    2. private Class<?>[] _activeViews
    3. public CustomSerializer(Class<?>[] view) {
    4. _activeViews = view
    5. }
    6. @Override
    7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
    8. throws IOException, JsonProcessingException {
    9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
    10. if (filter instanceof CustomFilter) {
    11. CustomFilter customFilter = (CustomFilter) filter
    12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
    13. provider.defaultSerializeValue(value, jgen)
    14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
    15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
    16. }
    17. }
    18. }

    Positive Reactions
    1. I think it can give a thread safe and much simpler implementation.
    2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
    3. I'll end up doing something like your example, just with some tweaks.
    4. if it not a problem, please, do the refactoring with a multithreading.
    5. However, my solution is still useful if you have a lot of properties to filter.
    6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
    7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
    Negative Reactions
    1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
    Other Reactions
    1. I have some refactoring to do now...
    2. I ended up looking at BeanSerializerModifier.class.
    3. I will look at it tomorrow morning.
    4. I had already seen that but didn't have time and forgot.
    5. @RansomBriggs Hmm, I agree.

  18. Deserializing JSON flat object using immutable classes with Jackson

    So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. .. details

    1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
    2. import com.fasterxml.jackson.annotation.JsonUnwrapped
    3. import com.fasterxml.jackson.annotation.PropertyAccessor
    4. import com.fasterxml.jackson.databind.ObjectMapper
    5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
    6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
    7. A a = new A(new Foo("some_value"), "some_other_value")
    8. System.out.println(mapper.writeValueAsString(a))
    9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
    10. System.out.println(mapper.writeValueAsString(aCopy))
    11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
    12. Foo(String var1) {this.var1 = var1
    13. } private Foo() {this.var1 = null
    14. }}class A{ @JsonUnwrapped private final Foo foo
    15. private final String var2
    16. A(Foo foo, String var2) { this.foo = foo
    17. this.var2 = var2
    18. } private A() { this.foo = null
    19. this.var2 = null
    20. }}

    Positive Reactions
    1. Your solution is probably the only working in this situation.
    2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
    3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
    Other Reactions
    1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

    • See Also (7)
    1. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    2. Jackson Serialization issue with CommonsMultipartFile

      By default Jackson skips all transient fields during serialization. If there is a getter for the transient field however then by default Jackson includes it during serialization. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left"} // transient fields are skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. }class CommonsMultipartFile{ private String name = "Fred"
      13. }

    3. Jackson Serialization issue with CommonsMultipartFile

      One configuration option to skip the getter is to just apply the JsonIgnore annotation. If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. @JsonIgnore public CommonsMultipartFile getFileData() {return fileData
      14. }}class CommonsMultipartFile{ private String name = "Fred"
      15. }

    4. Jackson Serialization issue with CommonsMultipartFile

      If there is a getter for the transient field however then by default Jackson includes it during serialization. One configuration option to skip the getter is to just apply the JsonIgnore annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left","fileData":{"name":"Fred"}} // transient fields with getters are not skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. public CommonsMultipartFile getFileData() {return fileData
      13. }}class CommonsMultipartFile{ private String name = "Fred"
      14. }

    5. Jackson Serialization issue with CommonsMultipartFile

      Another approach is to mark the type to be skipped with JsonIgnoreType. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnoreType
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // Types marked with @JsonIgnoreType are ignored during serialization. }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. public CommonsMultipartFile getFileData() {return fileData
      14. }}@JsonIgnoreTypeclass CommonsMultipartFile{ private String name = "Fred"
      15. }

    6. Jackson Serialization issue with CommonsMultipartFile

      If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. Another approach is to mark the type to be skipped with JsonIgnoreType. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. mapper.getSerializationConfig().addMixInAnnotations(Placement.class, SkipFileDataMixIn.class)
      8. System.out.println(mapper.writeValueAsString(new Placement()))
      9. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}abstract class SkipFileDataMixIn{ @JsonIgnore public abstract CommonsMultipartFile getFileData()
      10. }class Placement implements Serializable{ private static final long serialVersionUID = 1L
      11. private long placementId = 42
      12. private String type = "OK"
      13. private String placement = "left"
      14. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      15. public CommonsMultipartFile getFileData() {return fileData
      16. }}class CommonsMultipartFile{ private String name = "Fred"
      17. }

    7. JSON - Check if an array exists

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.List
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2")
      10. OtherThing otherThing = target.get(0)
      11. System.out.println(otherThing.element1)
      12. // value1 System.out.println(otherThing.element2)
      13. // value2 System.out.println(otherThing.element3)
      14. // value3 } // else do something } // else do something }}class Thing{ Map<String, List<OtherThing>> objects
      15. }class OtherThing{ String element1
      16. String element2
      17. String element3
      18. }

  19. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    None .. details

    1. @JsonInclude(Include.NON_NULL)
    2. class Foo {
    3. public String bar
    4. Foo(String bar) {
    5. this.bar = bar
    6. }
    7. }

  20. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    For example just remove the null key entries if possible before calling Jackson. That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. .. details

    1. mapper.setSerializationInclusion(Include.NON_NULL)

    Other Reactions
    1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  21. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. .. details

    1. import com.fasterxml.jackson.annotation.JsonInclude.Include
    2. import com.fasterxml.jackson.databind.SerializationFeature
    3. import java.util.HashMap
    4. import java.util.Map
    5. public class JacksonFoo {
    6. public static void main(String[] args) throws Exception {
    7. Map<String, Foo> foos = new HashMap<String, Foo>()
    8. foos.put("foo1", new Foo("foo1"))
    9. foos.put("foo2", new Foo(null))
    10. foos.put("foo3", null)
    11. foos.put(null, new Foo("foo4"))
    12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
    13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
    14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
    15. mapper.setSerializationInclusion(Include.NON_NULL)
    16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
    17. System.out.println(mapper.writeValueAsString(foos))
    18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
    19. }
    20. }
    21. class Foo {
    22. public String bar
    23. Foo(String bar) {
    24. this.bar = bar
    25. }
    26. }

    Other Reactions
    1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  22. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    None .. details

    1. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)

  23. Deserialize JSON with Jackson without proper field

    None .. details

    1. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":true}"
    2. ObjectMapper mapper = new ObjectMapper()
    3. MessageWrapper wrappedMessage = mapper.readValue(inputJson, MessageWrapper.class)
    4. System.out.println(mapper.writeValueAsString(wrappedMessage))
    5. // output: {"success":true} }}class MessageWrapper{ @JsonUnwrapped @JsonProperty // exposes non-public field for Jackson use Message message
    6. }

    • See Also (1)
    1. Deserialize JSON with Jackson without proper field

      The following examples demonstrate these points. Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.annotation.JsonProperty
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      6. ObjectMapper mapper = new ObjectMapper()
      7. Message message = mapper.readValue(inputJson, Message.class)
      8. System.out.println(mapper.writeValueAsString(message))
      9. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      10. @JsonProperty("success") public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      11. } @JsonProperty("success") public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      12. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

  24. Java + JSON and &quot;errorjava.lang.RuntimeException: Stub!&quot; error

    But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . .. details

    1. import java.io.File
    2. import java.io.IOException
    3. import org.codehaus.jackson.JsonEncoding
    4. import org.codehaus.jackson.JsonFactory
    5. import org.codehaus.jackson.JsonGenerationException
    6. import org.codehaus.jackson.JsonGenerator
    7. import org.codehaus.jackson.JsonParseException
    8. import org.codehaus.jackson.map.JsonMappingException
    9. import org.codehaus.jackson.map.ObjectMapper
    10. class User { public enum Gender { MALE, FEMALE }
    11. public static class Name { private String _first, _last
    12. public String getFirst() { return _first
    13. } public String getLast() { return _last
    14. } public void setFirst(String s) { _first = s
    15. } public void setLast(String s) { _last = s
    16. } } private Gender _gender
    17. private Name _name
    18. private boolean _isVerified
    19. private byte[] _userImage
    20. public Name getName() { return _name
    21. } public boolean isVerified() { return _isVerified
    22. } public Gender getGender() { return _gender
    23. } public byte[] getUserImage() { return _userImage
    24. } public void setName(Name n) { _name = n
    25. } public void setVerified(boolean b) { _isVerified = b
    26. } public void setGender(Gender g) { _gender = g
    27. } public void setUserImage(byte[] b) { _userImage = b
    28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
    29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
    30. System.out.println(user.getName().getFirst())
    31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
    32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
    33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
    34. } }}

  25. Jackson: deserialization of Map

    The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . .. details

    1. import java.io.File
    2. import java.util.HashMap
    3. import java.util.Map
    4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
    5. import org.codehaus.jackson.annotate.JsonMethod
    6. import org.codehaus.jackson.map.ObjectMapper
    7. import org.codehaus.jackson.type.TypeReference
    8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
    9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
    10. System.out.println(cache)
    11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
    12. String filePath
    13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
    14. }}

  26. Jackson deserialize object or array

    Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. .. details

    1. import java.io.IOException
    2. import org.codehaus.jackson.JsonNode
    3. import org.codehaus.jackson.JsonParser
    4. import org.codehaus.jackson.JsonProcessingException
    5. import org.codehaus.jackson.Version
    6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
    7. import org.codehaus.jackson.annotate.JsonMethod
    8. import org.codehaus.jackson.map.DeserializationContext
    9. import org.codehaus.jackson.map.JsonDeserializer
    10. import org.codehaus.jackson.map.ObjectMapper
    11. import org.codehaus.jackson.map.module.SimpleModule
    12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
    13. // {"property1":[]} String json2 = "{\"property1\":[]}"
    14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
    15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
    16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
    17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
    18. System.out.println(firstThing)
    19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
    20. System.out.println(secondThing)
    21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
    22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
    23. }}class Thing2{ int property2
    24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
    25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
    26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
    27. return null
    28. }}

    Positive Reactions
    1. Awesome job Bruce, thanks a bunch!.
    2. Do you happen to know of a good tutorial on writing one?
    3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
    4. Ok!
    Negative Reactions
    1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
    2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
    Other Reactions
    1. -- Answer updated with example.
    2. no chance on fixing the original input, right?

  27. Using Jackson&#39;s @JsonTypeInfo with a custom serializer

    The following additions/modifications to the test source code generate the desired output. . .. details

    1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
    2. public AnimalMap() { super()
    3. this.map = new HashMap<Object, Animal>()
    4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
    5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
    6. for (Animal a : t.animals) animals.put(a.getName(), a)
    7. jg.writeObject(animals)
    8. }}

    Positive Reactions
    1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
    Other Reactions
    1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

  28. GSON/Jackson in Android

    None .. details

    1. import java.io.File
    2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
    3. import org.codehaus.jackson.map.ObjectMapper
    4. public class JacksonFoo {
    5. public static void main(String[] args) throws Exception {
    6. ObjectMapper mapper = new ObjectMapper()
    7. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
    8. Thing thing = mapper.readValue(new File("input.json"), Thing.class)
    9. System.out.println(mapper.writeValueAsString(thing))
    10. }
    11. }

  29. Binding the nested json to @RequestBody object using Jackson converter

    Following is an example of using Jackson to deserialize a corrected version of the JSON into the same Parent/Child class structure in the current version of the question. Is it possible that the message about the syntax error is just that a message about a syntax error. .. details

    1. import java.util.ArrayList
    2. import org.codehaus.jackson.map.ObjectMapper
    3. public class Foo{ public static void main(String[] args) throws Exception {/*{ "name": "foo", "age": "45", "children": [ { "name": "bar", "age": "15" }, { "name": "baz", "age": "10" } ]} */ String jsonInput = "{\"name\":\"foo\",\"age\":\"45\",\"children\":[{\"name\":\"bar\",\"age\":\"15\"},{\"name\":\"baz\",\"age\":\"10\"}]}"
    4. ObjectMapper mapper = new ObjectMapper()
    5. Parent parent = mapper.readValue(jsonInput, Parent.class)
    6. System.out.println(mapper.writeValueAsString(parent))
    7. // output: // {"name":"foo","age":45,"children":[{"name":"bar","age":15},{"name":"baz","age":10}]} }}class Parent{ public String name
    8. public int age
    9. public ArrayList<Child> children = new ArrayList<Child>()
    10. }class Child{ public String name
    11. public int age
    12. }

    Positive Reactions
    1. It's working now.
    2. Thanks for the help guys...
    Negative Reactions
    1. I figured out a problem for some reason the rest-client that I was using was making the things worse.
    Other Reactions
    1. It was the issue with the input json.
    2. Not the application itself.

    • See Also (3)
    1. Jackson JSON, REST Data Binding & HashMaps problem

      The following demonstrates this point. There's some other problem in the system you're using. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.HashMap
      3. import java.util.List
      4. import java.util.Map
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. Map<String, String> requestMap = new HashMap<String, String>()
      8. requestMap.put("one", "1")
      9. requestMap.put("two", "2")
      10. System.out.println(mapper.writeValueAsString(requestMap))
      11. // output: {"two":"2","one":"1"} List<UserPermission> userPermissions = new ArrayList<UserPermission>()
      12. userPermissions.add(new UserPermissionImpl("domain1"))
      13. userPermissions.add(new UserPermissionImpl("domain2"))
      14. System.out.println(mapper.writeValueAsString(userPermissions))
      15. // output: [{"scope":"domain1"},{"scope":"domain2"}] Container container = new ContainerImpl(requestMap, userPermissions)
      16. // From an Interface-type reference, where the implementation is an object with two Interface-type references: System.out.println(mapper.writeValueAsString(container))
      17. // {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]} }}interface UserPermission {}class UserPermissionImpl implements UserPermission{ public String scope
      18. UserPermissionImpl(String scope) { this.scope = scope
      19. }}interface Container {}class ContainerImpl implements Container{ public Map<String, String> requestMap
      20. public List<UserPermission> userPermissions
      21. ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions) { this.requestMap = requestMap
      22. this.userPermissions = userPermissions
      23. }}

      Positive Reactions
      1. That maybe correct.
      2. If you do ever happen to figure out what's going on, do please post an update.
      3. Spring and Jersey add funny things to JSON handling.
      Other Reactions
      1. I'm sure I'm not the only curious one.
      2. There are a few things that require special configurations in order to get default Jackson behavior.
      3. :-).
      4. I'm not really sure, this thread is a few months old and I've shifted projects so I can't test it on that code base, but I'll play around when I have time.

    2. need to JSON output?

      Following is a demo of Jackson in action to solve the problem originally presented. The JSON output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonDemo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. List<ProductFromServiceTemp> products = getListFromWebservice()
      6. String json = mapper.writeValueAsString(products)
      7. System.out.println(json)
      8. } private static List<ProductFromServiceTemp> getListFromWebservice() { List<ProductFromServiceTemp> productList = new ArrayList<ProductFromServiceTemp>()
      9. for (int i = 0
      10. i < 10
      11. i++) { ProductFromServiceTemp product = new ProductFromServiceTemp()
      12. product.setName("name " + i)
      13. product.setDescription("desc " + i)
      14. product.setPrice(i * 100d)
      15. productList.add(product)
      16. } return productList
      17. }}class ProductFromServiceTemp{ private String name
      18. private String description
      19. private double price
      20. // Don't use double type for financial information. public String getName() {return name
      21. } public void setName(String name) {this.name = name
      22. } public String getDescription() {return description
      23. } public void setDescription(String description) {this.description = description
      24. } public double getPrice() {return price
      25. } public void setPrice(double price) {this.price = price
      26. }}

    3. Strict JSON parsing with Google's Gson?

      Here's an example with Jackson. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. // output: // Validating jsonInput1...// Validating jsonInput2...// Validating jsonInput3...// $.element2: is missing and it is not optional// [MyObject: element1=value1, element2=value2, element3=value3]// [MyObject: element1=value1, element2=value2, element3=null]// [MyObject: element1=value1, element2=null, element3=value3]import java.util.List
      2. import eu.vahlas.json.schema.JSONSchema
      3. import eu.vahlas.json.schema.JSONSchemaProvider
      4. import eu.vahlas.json.schema.impl.JacksonSchemaProvider
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo {
      7. static String jsonSchema =
      8. "{"
      9. + "\"description\":\"Serialized MyObject Specification\","
      10. + "\"type\":[\"object\"],"
      11. + "\"properties\":"
      12. + "{"
      13. + "\"element1\":{\"type\":\"string\"},"
      14. + "\"element2\":{\"type\":\"string\",\"optional\":false},"
      15. + "\"element3\":{\"type\":\"string\",\"optional\":true}"
      16. + "}"
      17. + "}"
      18. static String jsonInput1 =
      19. "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}"
      20. static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}"
      21. static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}"
      22. public static void main(String[] args) throws Exception {
      23. ObjectMapper mapper = new ObjectMapper()
      24. JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper)
      25. JSONSchema schema = schemaProvider.getSchema(jsonSchema)
      26. System.out.println("Validating jsonInput1...")
      27. validateAndLogErrors(jsonInput1, schema)
      28. System.out.println("Validating jsonInput2...")
      29. validateAndLogErrors(jsonInput2, schema)
      30. System.out.println("Validating jsonInput3...")
      31. validateAndLogErrors(jsonInput3, schema)
      32. MyObject object1 = mapper.readValue(jsonInput1, MyObject.class)
      33. System.out.println(object1)
      34. MyObject object2 = mapper.readValue(jsonInput2, MyObject.class)
      35. System.out.println(object2)
      36. MyObject object3 = mapper.readValue(jsonInput3, MyObject.class)
      37. System.out.println(object3)
      38. }
      39. static void validateAndLogErrors(String jsonInput, JSONSchema schema) {
      40. List<String> errors = schema.validate(jsonInput)
      41. for (String error : errors) {
      42. System.out.println(error)
      43. }
      44. }
      45. }
      46. class MyObject {
      47. String element1
      48. String element2
      49. String element3
      50. void setElement1(String element1) {
      51. this.element1 = element1
      52. }
      53. void setElement2(String element2) {
      54. this.element2 = element2
      55. }
      56. void setElement3(String element3) {
      57. this.element3 = element3
      58. }
      59. @Override
      60. public String toString() {
      61. return String.format(
      62. "[MyObject: element1=%s, element2=%s, element3=%s]", element1, element2, element3)
      63. }
      64. }

      Positive Reactions
      1. Although your proposed gson solution works when you create the type by another gson instance, it does not work when reusing the same context.
      Negative Reactions
      1. By creating a new gson you lose other configuration options your original gson had.
      Other Reactions
      1. It causes an infinite loop.

  30. Setting up JSON custom deserializer

    This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . .. details

    1. import java.io.IOException
    2. import org.codehaus.jackson.JsonParser
    3. import org.codehaus.jackson.JsonProcessingException
    4. import org.codehaus.jackson.Version
    5. import org.codehaus.jackson.map.DeserializationContext
    6. import org.codehaus.jackson.map.JsonDeserializer
    7. import org.codehaus.jackson.map.ObjectMapper
    8. import org.codehaus.jackson.map.module.SimpleModule
    9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
    10. bean.value = 42L
    11. ObjectMapper mapper = new ObjectMapper()
    12. String beanJson = mapper.writeValueAsString(bean)
    13. System.out.println(beanJson)
    14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
    15. System.out.println(beanCopy1.value)
    16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
    17. module.addDeserializer(Long.class, new LongJsonDeserializer())
    18. mapper = new ObjectMapper()
    19. mapper.registerModule(module)
    20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
    21. System.out.println(beanCopy2.value)
    22. // output: 126 }}class TestBean{ Long value
    23. public Long getValue() {return value
    24. } public void setValue(Long value) {this.value = value
    25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
    26. return value * 3
    27. }}

    Positive Reactions
    1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
    2. I read the original question too fast, maybe.
    Other Reactions
    1. Ah.
    2. Taking another look...
    3. I'll update this post with a full demo application.
    4. What I originally posted addressed the question you asked correctly.

  31. How can I polymorphic deserialization Json String using Java and Jackson Library?

    Here's a solution to the first problem. Here's a solution to the second problem. .. details

    1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
    2. import org.codehaus.jackson.map.ObjectMapper
    3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
    4. A a = new A()
    5. B b = new B()
    6. C c = new C()
    7. ObjectMapper mapper = new ObjectMapper()
    8. String baseJson = mapper.writeValueAsString(base)
    9. System.out.println(baseJson)
    10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
    11. System.out.println(aJson)
    12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
    13. System.out.println(bJson)
    14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
    15. System.out.println(cJson)
    16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
    17. System.out.println(baseCopy)
    18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
    19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
    20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
    21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
    22. System.out.println(aCopy)
    23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
    24. System.out.println(bCopy)
    25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
    26. System.out.println(cCopy)
    27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
    28. @Override public String toString() {return "baseName: " + baseName
    29. }}class A extends BaseClass{ public String aName = "a name"
    30. @Override public String toString() {return super.toString() + ", aName: " + aName
    31. }}class B extends BaseClass{ public String bName = "b name"
    32. @Override public String toString() {return super.toString() + ", bName: " + bName
    33. }}class C extends BaseClass{ public String cName = "c name"
    34. @Override public String toString() {return super.toString() + ", cName: " + cName
    35. }}

    Positive Reactions
    1. Thank you!.
    Negative Reactions
    1. It's the second problem I'm concerning.
    2. I've edited the question to reflect my concern.
    3. Sorry, I wasn't clear enough.
    4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
    Other Reactions
    1. You just hit the spot.

  32. Deserializing JSON into object with overloaded methods using Jackson

    input.json "value":"forty-two" Foo.java If you don't want to alter the pristine POJO defs with a Jackson annotation then you can use a MixIn. . .. details

    1. import java.io.File
    2. import org.codehaus.jackson.annotate.JsonIgnore
    3. import org.codehaus.jackson.map.ObjectMapper
    4. public class Foo {
    5. String value
    6. public String getValue() {
    7. return value
    8. }
    9. public void setValue(String value) {
    10. this.value = value
    11. }
    12. public void setValue(int value) {
    13. this.value = String.valueOf(value)
    14. }
    15. public static void main(String[] args) throws Exception {
    16. ObjectMapper mapper = new ObjectMapper()
    17. mapper
    18. .getDeserializationConfig()
    19. .addMixInAnnotations(Foo.class, IgnoreFooSetValueIntMixIn.class)
    20. Foo foo = mapper.readValue(new File("input.json"), Foo.class)
    21. System.out.println(mapper.writeValueAsString(foo))
    22. }
    23. }
    24. abstract class IgnoreFooSetValueIntMixIn {
    25. @JsonIgnore
    26. public abstract void setValue(int value)
    27. }

    Positive Reactions
    1. Jackson's Mix-In facility may well suit your needs.
    2. This solution seems to be ignoring both setValue properties (i.e., nothing gets set even though the JSON contains a value).
    3. Thanks, this is exactly what I was looking for.
    4. Turns out you do need the @JsonProperty("value") on the one you want to keep.
    Negative Reactions
    1. as of jackson 1.9, this solution no longer works.
    Other Reactions
    1. Is there a method for that?
    2. It allows you to effectively annotate third party type definitions, without altering the originals.
    3. @JsonIgnore on any setter / getter / associated field applies the same to the property.
    4. What about when you cannot alter the class, when it's third party?

    • See Also (1)
    1. Deserializing JSON into object with overloaded methods using Jackson

      Here's a simple example to demonstrate this point. input.json "value":"forty-two" Foo.java If you don't want to alter the pristine POJO defs with a Jackson annotation then you can use a MixIn. details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonIgnore
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo {
      5. String value
      6. public String getValue() {
      7. return value
      8. }
      9. public void setValue(String value) {
      10. this.value = value
      11. }
      12. @JsonIgnore
      13. public void setValue(int value) {
      14. this.value = String.valueOf(value)
      15. }
      16. public static void main(String[] args) throws Exception {
      17. ObjectMapper mapper = new ObjectMapper()
      18. Foo foo = mapper.readValue(new File("input.json"), Foo.class)
      19. System.out.println(mapper.writeValueAsString(foo))
      20. }
      21. }

      Positive Reactions
      1. Jackson's Mix-In facility may well suit your needs.
      2. This solution seems to be ignoring both setValue properties (i.e., nothing gets set even though the JSON contains a value).
      3. Thanks, this is exactly what I was looking for.
      4. Turns out you do need the @JsonProperty("value") on the one you want to keep.
      Negative Reactions
      1. as of jackson 1.9, this solution no longer works.
      Other Reactions
      1. Is there a method for that?
      2. It allows you to effectively annotate third party type definitions, without altering the originals.
      3. @JsonIgnore on any setter / getter / associated field applies the same to the property.
      4. What about when you cannot alter the class, when it's third party?

  1. override
      Chart will be rendered here
    1. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    2. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    3. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    4. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    5. Strict JSON parsing with Google's Gson?

      Here's an example with Jackson. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. // output: // Validating jsonInput1...// Validating jsonInput2...// Validating jsonInput3...// $.element2: is missing and it is not optional// [MyObject: element1=value1, element2=value2, element3=value3]// [MyObject: element1=value1, element2=value2, element3=null]// [MyObject: element1=value1, element2=null, element3=value3]import java.util.List
      2. import eu.vahlas.json.schema.JSONSchema
      3. import eu.vahlas.json.schema.JSONSchemaProvider
      4. import eu.vahlas.json.schema.impl.JacksonSchemaProvider
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo {
      7. static String jsonSchema =
      8. "{"
      9. + "\"description\":\"Serialized MyObject Specification\","
      10. + "\"type\":[\"object\"],"
      11. + "\"properties\":"
      12. + "{"
      13. + "\"element1\":{\"type\":\"string\"},"
      14. + "\"element2\":{\"type\":\"string\",\"optional\":false},"
      15. + "\"element3\":{\"type\":\"string\",\"optional\":true}"
      16. + "}"
      17. + "}"
      18. static String jsonInput1 =
      19. "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}"
      20. static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}"
      21. static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}"
      22. public static void main(String[] args) throws Exception {
      23. ObjectMapper mapper = new ObjectMapper()
      24. JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper)
      25. JSONSchema schema = schemaProvider.getSchema(jsonSchema)
      26. System.out.println("Validating jsonInput1...")
      27. validateAndLogErrors(jsonInput1, schema)
      28. System.out.println("Validating jsonInput2...")
      29. validateAndLogErrors(jsonInput2, schema)
      30. System.out.println("Validating jsonInput3...")
      31. validateAndLogErrors(jsonInput3, schema)
      32. MyObject object1 = mapper.readValue(jsonInput1, MyObject.class)
      33. System.out.println(object1)
      34. MyObject object2 = mapper.readValue(jsonInput2, MyObject.class)
      35. System.out.println(object2)
      36. MyObject object3 = mapper.readValue(jsonInput3, MyObject.class)
      37. System.out.println(object3)
      38. }
      39. static void validateAndLogErrors(String jsonInput, JSONSchema schema) {
      40. List<String> errors = schema.validate(jsonInput)
      41. for (String error : errors) {
      42. System.out.println(error)
      43. }
      44. }
      45. }
      46. class MyObject {
      47. String element1
      48. String element2
      49. String element3
      50. void setElement1(String element1) {
      51. this.element1 = element1
      52. }
      53. void setElement2(String element2) {
      54. this.element2 = element2
      55. }
      56. void setElement3(String element3) {
      57. this.element3 = element3
      58. }
      59. @Override
      60. public String toString() {
      61. return String.format(
      62. "[MyObject: element1=%s, element2=%s, element3=%s]", element1, element2, element3)
      63. }
      64. }

      Positive Reactions
      1. Although your proposed gson solution works when you create the type by another gson instance, it does not work when reusing the same context.
      Negative Reactions
      1. By creating a new gson you lose other configuration options your original gson had.
      Other Reactions
      1. It causes an infinite loop.

    6. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    7. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the second problem. If instead the goal is to deserialize to a subclass type without a JSON element specifically dedicated to indicate what the subclass type is then that is also possible so long as something in the JSON can be used to decide what the subclass type should be. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import org.codehaus.jackson.annotate.JsonSubTypes
      2. import org.codehaus.jackson.annotate.JsonSubTypes.Type
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      6. A a = new A()
      7. B b = new B()
      8. C c = new C()
      9. ObjectMapper mapper = new ObjectMapper()
      10. String baseJson = mapper.writeValueAsString(base)
      11. System.out.println(baseJson)
      12. // {"type":"BaseClass","baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      13. System.out.println(aJson)
      14. // {"type":"a","baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      15. System.out.println(bJson)
      16. // {"type":"b","baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      17. System.out.println(cJson)
      18. // {"type":"c","baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      19. System.out.println(baseCopy)
      20. // baseName: base name BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      21. System.out.println(aCopy)
      22. // baseName: base name, aName: a name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      23. System.out.println(bCopy)
      24. // baseName: base name, bName: b name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      25. System.out.println(cCopy)
      26. // baseName: base name, cName: c name }}@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = A.class, name = "a"), @Type(value = B.class, name = "b"), @Type(value = C.class, name = "c") }) class BaseClass{ public String baseName = "base name"
      27. @Override public String toString() {return "baseName: " + baseName
      28. }}class A extends BaseClass{ public String aName = "a name"
      29. @Override public String toString() {return super.toString() + ", aName: " + aName
      30. }}class B extends BaseClass{ public String bName = "b name"
      31. @Override public String toString() {return super.toString() + ", bName: " + bName
      32. }}class C extends BaseClass{ public String cName = "c name"
      33. @Override public String toString() {return super.toString() + ", cName: " + cName
      34. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    8. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    9. How do I serialize an associated object differently using Jackson and annotations?

      The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class CustomSerializer extends JsonSerializer<Object> {
      2. private Class<?>[] _activeViews
      3. public CustomSerializer(Class<?>[] view) {
      4. _activeViews = view
      5. }
      6. @Override
      7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
      8. throws IOException, JsonProcessingException {
      9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
      10. if (filter instanceof CustomFilter) {
      11. CustomFilter customFilter = (CustomFilter) filter
      12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
      13. provider.defaultSerializeValue(value, jgen)
      14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
      15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
      16. }
      17. }
      18. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    10. Jackson API: partially update a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Override public String getModuleName() { return "MyModule"
      2. } @Override public Version version() { return new Version(0, 0, 1, "SNAPSHOT")
      3. } @Override public void setupModule(Module.SetupContext context) { context.addBeanSerializerModifier(new org.codehaus.jackson.map.ser.BeanSerializerModifier() { private UnknownPartSerializer cs
      4. @Override public JsonSerializer modifySerializer(SerializationConfig config, BasicBeanDescription beanDesc, JsonSerializer<?> serializer) { return UnknownPart.class.isAssignableFrom(beanDesc.getBeanClass()) ? new UnknownPartSerializer((BeanSerializerBase) serializer) : serializer
      5. } })
      6. } }

    11. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the first problem. Here's a solution to the second problem. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      4. A a = new A()
      5. B b = new B()
      6. C c = new C()
      7. ObjectMapper mapper = new ObjectMapper()
      8. String baseJson = mapper.writeValueAsString(base)
      9. System.out.println(baseJson)
      10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      11. System.out.println(aJson)
      12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      13. System.out.println(bJson)
      14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      15. System.out.println(cJson)
      16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      17. System.out.println(baseCopy)
      18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
      20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      22. System.out.println(aCopy)
      23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      24. System.out.println(bCopy)
      25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      26. System.out.println(cCopy)
      27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
      28. @Override public String toString() {return "baseName: " + baseName
      29. }}class A extends BaseClass{ public String aName = "a name"
      30. @Override public String toString() {return super.toString() + ", aName: " + aName
      31. }}class B extends BaseClass{ public String bName = "b name"
      32. @Override public String toString() {return super.toString() + ", bName: " + bName
      33. }}class C extends BaseClass{ public String cName = "c name"
      34. @Override public String toString() {return super.toString() + ", cName: " + cName
      35. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    12. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    13. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    14. How do I parse JSON into a Map with lowercase keys using Jackson?

      Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.KeyDeserializer
      2. import org.codehaus.jackson.map.ObjectMapper
      3. import org.codehaus.jackson.map.module.SimpleModule
      4. import org.codehaus.jackson.Version
      5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
      6. }}// ...ObjectMapper mapper = new ObjectMapper()
      7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
      8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
      9. mapper.registerModule(module)
      10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

    15. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

    16. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

  2. serializationfeature
      Chart will be rendered here
    1. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)

    2. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  3. linkedhashmap
      Chart will be rendered here
    1. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    2. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

  4. valueasstring
      Chart will be rendered here
    1. Jackson JSON, REST Data Binding & HashMaps problem

      The following demonstrates this point. There's some other problem in the system you're using. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.HashMap
      3. import java.util.List
      4. import java.util.Map
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. Map<String, String> requestMap = new HashMap<String, String>()
      8. requestMap.put("one", "1")
      9. requestMap.put("two", "2")
      10. System.out.println(mapper.writeValueAsString(requestMap))
      11. // output: {"two":"2","one":"1"} List<UserPermission> userPermissions = new ArrayList<UserPermission>()
      12. userPermissions.add(new UserPermissionImpl("domain1"))
      13. userPermissions.add(new UserPermissionImpl("domain2"))
      14. System.out.println(mapper.writeValueAsString(userPermissions))
      15. // output: [{"scope":"domain1"},{"scope":"domain2"}] Container container = new ContainerImpl(requestMap, userPermissions)
      16. // From an Interface-type reference, where the implementation is an object with two Interface-type references: System.out.println(mapper.writeValueAsString(container))
      17. // {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]} }}interface UserPermission {}class UserPermissionImpl implements UserPermission{ public String scope
      18. UserPermissionImpl(String scope) { this.scope = scope
      19. }}interface Container {}class ContainerImpl implements Container{ public Map<String, String> requestMap
      20. public List<UserPermission> userPermissions
      21. ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions) { this.requestMap = requestMap
      22. this.userPermissions = userPermissions
      23. }}

      Positive Reactions
      1. That maybe correct.
      2. If you do ever happen to figure out what's going on, do please post an update.
      3. Spring and Jersey add funny things to JSON handling.
      Other Reactions
      1. I'm sure I'm not the only curious one.
      2. There are a few things that require special configurations in order to get default Jackson behavior.
      3. :-).
      4. I'm not really sure, this thread is a few months old and I've shifted projects so I can't test it on that code base, but I'll play around when I have time.

    2. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the second problem. If instead the goal is to deserialize to a subclass type without a JSON element specifically dedicated to indicate what the subclass type is then that is also possible so long as something in the JSON can be used to decide what the subclass type should be. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import org.codehaus.jackson.annotate.JsonSubTypes
      2. import org.codehaus.jackson.annotate.JsonSubTypes.Type
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      6. A a = new A()
      7. B b = new B()
      8. C c = new C()
      9. ObjectMapper mapper = new ObjectMapper()
      10. String baseJson = mapper.writeValueAsString(base)
      11. System.out.println(baseJson)
      12. // {"type":"BaseClass","baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      13. System.out.println(aJson)
      14. // {"type":"a","baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      15. System.out.println(bJson)
      16. // {"type":"b","baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      17. System.out.println(cJson)
      18. // {"type":"c","baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      19. System.out.println(baseCopy)
      20. // baseName: base name BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      21. System.out.println(aCopy)
      22. // baseName: base name, aName: a name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      23. System.out.println(bCopy)
      24. // baseName: base name, bName: b name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      25. System.out.println(cCopy)
      26. // baseName: base name, cName: c name }}@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = A.class, name = "a"), @Type(value = B.class, name = "b"), @Type(value = C.class, name = "c") }) class BaseClass{ public String baseName = "base name"
      27. @Override public String toString() {return "baseName: " + baseName
      28. }}class A extends BaseClass{ public String aName = "a name"
      29. @Override public String toString() {return super.toString() + ", aName: " + aName
      30. }}class B extends BaseClass{ public String bName = "b name"
      31. @Override public String toString() {return super.toString() + ", bName: " + bName
      32. }}class C extends BaseClass{ public String cName = "c name"
      33. @Override public String toString() {return super.toString() + ", cName: " + cName
      34. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    3. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the first problem. Here's a solution to the second problem. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      4. A a = new A()
      5. B b = new B()
      6. C c = new C()
      7. ObjectMapper mapper = new ObjectMapper()
      8. String baseJson = mapper.writeValueAsString(base)
      9. System.out.println(baseJson)
      10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      11. System.out.println(aJson)
      12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      13. System.out.println(bJson)
      14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      15. System.out.println(cJson)
      16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      17. System.out.println(baseCopy)
      18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
      20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      22. System.out.println(aCopy)
      23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      24. System.out.println(bCopy)
      25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      26. System.out.println(cCopy)
      27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
      28. @Override public String toString() {return "baseName: " + baseName
      29. }}class A extends BaseClass{ public String aName = "a name"
      30. @Override public String toString() {return super.toString() + ", aName: " + aName
      31. }}class B extends BaseClass{ public String bName = "b name"
      32. @Override public String toString() {return super.toString() + ", bName: " + bName
      33. }}class C extends BaseClass{ public String cName = "c name"
      34. @Override public String toString() {return super.toString() + ", cName: " + cName
      35. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    4. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  5. jsonmappingexception
      Chart will be rendered here
    1. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    2. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    3. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    4. Jackson Library JSON Mapper to String

      Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import java.io.IOException
      2. import java.util.List
      3. import org.codehaus.jackson.JsonGenerationException
      4. import org.codehaus.jackson.map.JsonMappingException
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class A {
      7. private List<B> b
      8. private int c
      9. public List<B> getB() {
      10. return b
      11. }
      12. public void setB(List<B> b) {
      13. this.b = b
      14. }
      15. public int getC() {
      16. return c
      17. }
      18. public void setC(int c) {
      19. this.c = c
      20. }
      21. public static void main(String[] args)
      22. throws JsonGenerationException, JsonMappingException, IOException {
      23. A a = new A()
      24. ObjectMapper mapper = new ObjectMapper()
      25. String temp = mapper.writeValueAsString(a)
      26. System.out.println(temp)
      27. }
      28. }
      29. class B {}

      Positive Reactions
      1. The method read works only if the List** b is empty..**
      2. I have change something in my Class A and the method save go.
      3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
      Negative Reactions
      1. Now i have another problem..
      Other Reactions
      1. I have substitute List** b new List**() with List** new ArrayList**().
      2. Are you using Eclipse?
      3. Meaning you do not have the appropriate jar file in your classpath.
      4. Why??
      5. The same function called in two activities..********
      6. See updated answer.
      7. If you copied my complete example and it did not run, then its a build path issue.
      8. Also, make sure you have get/set methods for each field in Class B.
      9. @user2520969 Did the example help?

    5. Pretty print JSON output in JBoss RESTful service

      I have a bit of a round about solution that prints it pretty decently. Not the best Pretty Print but it is enough You'll need the following from Maven Then you can change your method to something like this Since what it does is 1. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.JsonGenerationException
      2. import org.codehaus.jackson.map.JsonMappingException
      3. import org.codehaus.jackson.map.ObjectMapper
      4. import org.codehaus.jackson.map.ObjectWriter
      5. ...private final ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter()
      6. ...@GET@Path("books")@Produces({ MediaType.APPLICATION_JSON })public Response getBooks() { return Response.status(Status.OK).entity(WRITER.writeValueAsString(doGetBooks())).build()
      7. }

    6. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

    7. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  6. deserializationcontext
      Chart will be rendered here
    1. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    2. How do I parse JSON into a Map with lowercase keys using Jackson?

      Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.KeyDeserializer
      2. import org.codehaus.jackson.map.ObjectMapper
      3. import org.codehaus.jackson.map.module.SimpleModule
      4. import org.codehaus.jackson.Version
      5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
      6. }}// ...ObjectMapper mapper = new ObjectMapper()
      7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
      8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
      9. mapper.registerModule(module)
      10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

    3. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

  7. visibility
      Chart will be rendered here
    1. JSON - Check if an array exists

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.List
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2")
      10. OtherThing otherThing = target.get(0)
      11. System.out.println(otherThing.element1)
      12. // value1 System.out.println(otherThing.element2)
      13. // value2 System.out.println(otherThing.element3)
      14. // value3 } // else do something } // else do something }}class Thing{ Map<String, List<OtherThing>> objects
      15. }class OtherThing{ String element1
      16. String element2
      17. String element3
      18. }

    2. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    3. Deserializing JSON flat object using immutable classes with Jackson

      So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
      2. import com.fasterxml.jackson.annotation.JsonUnwrapped
      3. import com.fasterxml.jackson.annotation.PropertyAccessor
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
      6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
      7. A a = new A(new Foo("some_value"), "some_other_value")
      8. System.out.println(mapper.writeValueAsString(a))
      9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
      10. System.out.println(mapper.writeValueAsString(aCopy))
      11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
      12. Foo(String var1) {this.var1 = var1
      13. } private Foo() {this.var1 = null
      14. }}class A{ @JsonUnwrapped private final Foo foo
      15. private final String var2
      16. A(Foo foo, String var2) { this.foo = foo
      17. this.var2 = var2
      18. } private A() { this.foo = null
      19. this.var2 = null
      20. }}

      Positive Reactions
      1. Your solution is probably the only working in this situation.
      2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
      3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
      Other Reactions
      1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

    4. Jackson Serialization issue with CommonsMultipartFile

      By default Jackson skips all transient fields during serialization. If there is a getter for the transient field however then by default Jackson includes it during serialization. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left"} // transient fields are skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. }class CommonsMultipartFile{ private String name = "Fred"
      13. }

    5. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    6. Jackson Serialization issue with CommonsMultipartFile

      If there is a getter for the transient field however then by default Jackson includes it during serialization. One configuration option to skip the getter is to just apply the JsonIgnore annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left","fileData":{"name":"Fred"}} // transient fields with getters are not skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. public CommonsMultipartFile getFileData() {return fileData
      13. }}class CommonsMultipartFile{ private String name = "Fred"
      14. }

    7. Jackson Serialization issue with CommonsMultipartFile

      Another approach is to mark the type to be skipped with JsonIgnoreType. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnoreType
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // Types marked with @JsonIgnoreType are ignored during serialization. }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. public CommonsMultipartFile getFileData() {return fileData
      14. }}@JsonIgnoreTypeclass CommonsMultipartFile{ private String name = "Fred"
      15. }

    8. Jackson Serialization issue with CommonsMultipartFile

      If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. Another approach is to mark the type to be skipped with JsonIgnoreType. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. mapper.getSerializationConfig().addMixInAnnotations(Placement.class, SkipFileDataMixIn.class)
      8. System.out.println(mapper.writeValueAsString(new Placement()))
      9. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}abstract class SkipFileDataMixIn{ @JsonIgnore public abstract CommonsMultipartFile getFileData()
      10. }class Placement implements Serializable{ private static final long serialVersionUID = 1L
      11. private long placementId = 42
      12. private String type = "OK"
      13. private String placement = "left"
      14. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      15. public CommonsMultipartFile getFileData() {return fileData
      16. }}class CommonsMultipartFile{ private String name = "Fred"
      17. }

    9. Jackson Serialization issue with CommonsMultipartFile

      One configuration option to skip the getter is to just apply the JsonIgnore annotation. If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. @JsonIgnore public CommonsMultipartFile getFileData() {return fileData
      14. }}class CommonsMultipartFile{ private String name = "Fred"
      15. }

    10. GSON/Jackson in Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonFoo {
      5. public static void main(String[] args) throws Exception {
      6. ObjectMapper mapper = new ObjectMapper()
      7. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. System.out.println(mapper.writeValueAsString(thing))
      10. }
      11. }

    11. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

  8. finding
      Chart will be rendered here
    1. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  9. propertynamingstrategy
      Chart will be rendered here
    1. Deserialize json with different object types

      Your class should be deserialized automatically if you modify it like this Note. Jackson 2.1 required**) Then to deserialize in your code . details

      Reactions - Positive 11, Negative 3, Others 0

      1. @JsonIgnoreProperties("team_id")@JsonNamingStrategy(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy)public class Registration implements Serializable { private static final long serialVersionUID = 1L
      2. private int id
      3. private String currentStatus
      4. private Date expirationTime
      5. @JsonIgnore private Volunteer volunteer
      6. @JsonIgnore private Team team
      7. public Registration() { } // other code}

      Positive Reactions
      1. Awesome it works!
      2. The result: succes is only meant to check if the user is signed in and if the input was correct (the response results from scanning a QR code).
      3. Well, no, it is not necessary.
      4. Jackson:1.9.12 I really appreciate your help :).
      5. Sounds strange to serialize Registration in SuccessfulOperation to me.
      6. and updated to Jackson 2.2.2 Thanks!
      7. Thanks for your quick answer!
      8. It is just the cleanest solution I know when dealing with "polymorphic JSON" ;) You still did not show what your Registration class looks like.
      9. The most recent version is 2.2.1!
      10. And good choice on Jackson... Android's JSON library is poor, to be honest.
      11. Hestitated to try GSon but Jackson is doing great :).
      Negative Reactions
      1. No problem!
      2. Argh, 1.9.12???
      3. I'm sorry, I added it as edit now.
      Other Reactions
      1. !.
      2. Is it really necessary to create those two subclasses?
      3. OK, hold on, I'll edit my answer with a fully annotated class; what Jackson version are you using?
      4. Upgrade :p My code will work with 2.1.x (edited), but I doubt it will with 1.9.12...
      5. I used jackson before in college when creating a java webapp.

  10. jsonignoreproperties
      Chart will be rendered here
    1. Jackson with JSON: Unrecognized field, not marked as ignorable

      I found this useful to avoid creating a wrapper class Map dummy<String,Student myClientResponse.getEntity(new GenericType<Map<String Student>>(){}) and then Student myStudent dummy.get("wrapper"). You can use Jackson's annotation. details

      Reactions - Positive 6, Negative 0, Others 0

      1. @JsonIgnoreProperties

      Positive Reactions
      1. great answer !.
      2. youse rockses!
      3. thank you :).
      4. i must add that you do need the (ignoreUnknown true) when annotating your class otherwise it won't work.
      5. In one view, I'd like to serialize with a certain set of fields.
      6. thanks !
      Other Reactions
      1. Ariel, is there any way to declare this external to the class?
      2. I haven't done it but I believe that you can get somewhere in the annotations processing code and add the behavior programatically, although I can't think why you would like to do it.
      3. Why this answer is not accepted yet?
      4. In another view, I want a different set of fields serialized (or perhaps rename the properties in the JSON).
      5. Can you give me an example?
      6. I'm serializing classes that I do not own (cannot modify).

    2. Mapping JSON data to Java objects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.net.*
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Movie {
      5. public static void main(String[] args) throws Exception {
      6. MovieResponse response
      7. ObjectMapper mapper = new ObjectMapper()
      8. response = mapper.readValue(new File("C:\\M.json"), MovieResponse.class)
      9. System.out.println(response)
      10. }
      11. }

    3. Jackson with JSON: Unrecognized field, not marked as ignorable

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @JsonIgnoreProperties(ignoreUnknown = true)

    4. Deserialize json with different object types

      Your class should be deserialized automatically if you modify it like this Note. Jackson 2.1 required**) Then to deserialize in your code . details

      Reactions - Positive 11, Negative 3, Others 0

      1. @JsonIgnoreProperties("team_id")@JsonNamingStrategy(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy)public class Registration implements Serializable { private static final long serialVersionUID = 1L
      2. private int id
      3. private String currentStatus
      4. private Date expirationTime
      5. @JsonIgnore private Volunteer volunteer
      6. @JsonIgnore private Team team
      7. public Registration() { } // other code}

      Positive Reactions
      1. Awesome it works!
      2. The result: succes is only meant to check if the user is signed in and if the input was correct (the response results from scanning a QR code).
      3. Well, no, it is not necessary.
      4. Jackson:1.9.12 I really appreciate your help :).
      5. Sounds strange to serialize Registration in SuccessfulOperation to me.
      6. and updated to Jackson 2.2.2 Thanks!
      7. Thanks for your quick answer!
      8. It is just the cleanest solution I know when dealing with "polymorphic JSON" ;) You still did not show what your Registration class looks like.
      9. The most recent version is 2.2.1!
      10. And good choice on Jackson... Android's JSON library is poor, to be honest.
      11. Hestitated to try GSon but Jackson is doing great :).
      Negative Reactions
      1. No problem!
      2. Argh, 1.9.12???
      3. I'm sorry, I added it as edit now.
      Other Reactions
      1. !.
      2. Is it really necessary to create those two subclasses?
      3. OK, hold on, I'll edit my answer with a fully annotated class; what Jackson version are you using?
      4. Upgrade :p My code will work with 2.1.x (edited), but I doubt it will with 1.9.12...
      5. I used jackson before in college when creating a java webapp.

  11. contextualserializer
      Chart will be rendered here
    1. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  12. iterator
      Chart will be rendered here
    1. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    2. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

  13. jsonserializer
      Chart will be rendered here
    1. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    2. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

    3. Jackson API: partially update a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Override public String getModuleName() { return "MyModule"
      2. } @Override public Version version() { return new Version(0, 0, 1, "SNAPSHOT")
      3. } @Override public void setupModule(Module.SetupContext context) { context.addBeanSerializerModifier(new org.codehaus.jackson.map.ser.BeanSerializerModifier() { private UnknownPartSerializer cs
      4. @Override public JsonSerializer modifySerializer(SerializationConfig config, BasicBeanDescription beanDesc, JsonSerializer<?> serializer) { return UnknownPart.class.isAssignableFrom(beanDesc.getBeanClass()) ? new UnknownPartSerializer((BeanSerializerBase) serializer) : serializer
      5. } })
      6. } }

    4. How do I serialize an associated object differently using Jackson and annotations?

      The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class CustomSerializer extends JsonSerializer<Object> {
      2. private Class<?>[] _activeViews
      3. public CustomSerializer(Class<?>[] view) {
      4. _activeViews = view
      5. }
      6. @Override
      7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
      8. throws IOException, JsonProcessingException {
      9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
      10. if (filter instanceof CustomFilter) {
      11. CustomFilter customFilter = (CustomFilter) filter
      12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
      13. provider.defaultSerializeValue(value, jgen)
      14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
      15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
      16. }
      17. }
      18. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

  14. typereference
      Chart will be rendered here
    1. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

  15. jsonparser
      Chart will be rendered here
    1. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    2. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

    3. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    4. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

  16. feature
      Chart will be rendered here
    1. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the first problem. Here's a solution to the second problem. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      4. A a = new A()
      5. B b = new B()
      6. C c = new C()
      7. ObjectMapper mapper = new ObjectMapper()
      8. String baseJson = mapper.writeValueAsString(base)
      9. System.out.println(baseJson)
      10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      11. System.out.println(aJson)
      12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      13. System.out.println(bJson)
      14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      15. System.out.println(cJson)
      16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      17. System.out.println(baseCopy)
      18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
      20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      22. System.out.println(aCopy)
      23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      24. System.out.println(bCopy)
      25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      26. System.out.println(cCopy)
      27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
      28. @Override public String toString() {return "baseName: " + baseName
      29. }}class A extends BaseClass{ public String aName = "a name"
      30. @Override public String toString() {return super.toString() + ", aName: " + aName
      31. }}class B extends BaseClass{ public String bName = "b name"
      32. @Override public String toString() {return super.toString() + ", bName: " + bName
      33. }}class C extends BaseClass{ public String cName = "c name"
      34. @Override public String toString() {return super.toString() + ", cName: " + cName
      35. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

  17. jsonparseexception
      Chart will be rendered here
    1. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

  18. jsonunwrapped
      Chart will be rendered here
    1. Deserialize JSON with Jackson without proper field

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":true}"
      2. ObjectMapper mapper = new ObjectMapper()
      3. MessageWrapper wrappedMessage = mapper.readValue(inputJson, MessageWrapper.class)
      4. System.out.println(mapper.writeValueAsString(wrappedMessage))
      5. // output: {"success":true} }}class MessageWrapper{ @JsonUnwrapped @JsonProperty // exposes non-public field for Jackson use Message message
      6. }

    2. Deserializing JSON flat object using immutable classes with Jackson

      So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
      2. import com.fasterxml.jackson.annotation.JsonUnwrapped
      3. import com.fasterxml.jackson.annotation.PropertyAccessor
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
      6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
      7. A a = new A(new Foo("some_value"), "some_other_value")
      8. System.out.println(mapper.writeValueAsString(a))
      9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
      10. System.out.println(mapper.writeValueAsString(aCopy))
      11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
      12. Foo(String var1) {this.var1 = var1
      13. } private Foo() {this.var1 = null
      14. }}class A{ @JsonUnwrapped private final Foo foo
      15. private final String var2
      16. A(Foo foo, String var2) { this.foo = foo
      17. this.var2 = var2
      18. } private A() { this.foo = null
      19. this.var2 = null
      20. }}

      Positive Reactions
      1. Your solution is probably the only working in this situation.
      2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
      3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
      Other Reactions
      1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

  19. jsoninclude
      Chart will be rendered here
    1. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @JsonInclude(Include.NON_NULL)
      2. class Foo {
      3. public String bar
      4. Foo(String bar) {
      5. this.bar = bar
      6. }
      7. }

    2. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  20. fieldname
      Chart will be rendered here
    1. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  21. jsonnode
      Chart will be rendered here
    1. Convert JSON from URL to JSONNode

      See methods etc etc. shameless plug And if you want to use JSON-Pointer to navigate your JSON coreutils you-can-also-do-that . details

      Reactions - Positive 5, Negative 1, Others 0

      1. final JsonPointer ptr = JsonPointer.of("current_observation", "display_location")
      2. final JsonNode displayLocation = ptr.get(node)

      Positive Reactions
      1. I will update them later, and hope that that solves the issue.
      2. OK, compiled successfully, many thanks.
      3. Update to the latest (2.2.x) ;).
      4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
      5. Please show the dependencies you have.
      Negative Reactions
      1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
      Other Reactions
      1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
      2. I changed it to:.
      3. There you are, as you can see some them are older than that.
      4. It does work; if it doesn't, it means you use an old version of jackson- databind.
      5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
      6. I've now altered the code.

    2. Getting both JSONObject and Google Gson feature in a single library

      You can use Jackson . It has a databinding solution like Gson and a tree-model-view like JSONObject . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Main {
      4. public static class Me {
      5. public String key
      6. }
      7. public static void main(String[] args) throws IOException {
      8. ObjectMapper mapper = new ObjectMapper()
      9. String json = "{\"key\" : \"value\"}"
      10. // Feature 1 JsonNode rootNode = mapper.readValue(json, JsonNode.class)
      11. System.out.println(rootNode.get("key").getTextValue())
      12. // Feature 2 Me value = mapper.readValue(json, Me.class)
      13. System.out.println(value.key)
      14. }
      15. }

      Positive Reactions
      1. I am very happy with it :).
      2. Thanks for recommending this library.
      3. It does support sub elements.
      4. Map userData mapper.readValue(json, Map.class); it's considered as simple databinding.
      Negative Reactions
      1. Hum my bad, it seems to work with Map, List and String arrays.
      Other Reactions
      1. But...but...but... URL_http://pastebin.com/CRUH4dyG I try.
      2. No, not really, as JSon elements can have other sub elements, the JsonNode system is way better.
      3. May I know which method is better?
      4. For feature 1, is it OK for me to HashMap untyped mapper.readValue(json, HashMap.class);.
      5. Is that what you mean?

    3. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    4. Convert JSON from URL to JSONNode

      Thanks again. I see no reason why you'd need to use a Map<String Object when Jackson has the almighty JsonNode See the databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html javadoc for-JsonNode . details

      Reactions - Positive 5, Negative 1, Others 0

      1. final JsonNode node = new ObjectMapper().readTree(new URL("yourURLHere")

      Positive Reactions
      1. I will update them later, and hope that that solves the issue.
      2. OK, compiled successfully, many thanks.
      3. Update to the latest (2.2.x) ;).
      4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
      5. Please show the dependencies you have.
      Negative Reactions
      1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
      Other Reactions
      1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
      2. I changed it to:.
      3. There you are, as you can see some them are older than that.
      4. It does work; if it doesn't, it means you use an old version of jackson- databind.
      5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
      6. I've now altered the code.

    5. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

  22. generator
      Chart will be rendered here
    1. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  23. serializerprovider
      Chart will be rendered here
    1. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    2. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    3. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    4. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    5. How do I serialize an associated object differently using Jackson and annotations?

      The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class CustomSerializer extends JsonSerializer<Object> {
      2. private Class<?>[] _activeViews
      3. public CustomSerializer(Class<?>[] view) {
      4. _activeViews = view
      5. }
      6. @Override
      7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
      8. throws IOException, JsonProcessingException {
      9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
      10. if (filter instanceof CustomFilter) {
      11. CustomFilter customFilter = (CustomFilter) filter
      12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
      13. provider.defaultSerializeValue(value, jgen)
      14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
      15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
      16. }
      17. }
      18. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    6. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  24. jsongenerationexception
      Chart will be rendered here
    1. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    2. Jackson Library JSON Mapper to String

      Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import java.io.IOException
      2. import java.util.List
      3. import org.codehaus.jackson.JsonGenerationException
      4. import org.codehaus.jackson.map.JsonMappingException
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class A {
      7. private List<B> b
      8. private int c
      9. public List<B> getB() {
      10. return b
      11. }
      12. public void setB(List<B> b) {
      13. this.b = b
      14. }
      15. public int getC() {
      16. return c
      17. }
      18. public void setC(int c) {
      19. this.c = c
      20. }
      21. public static void main(String[] args)
      22. throws JsonGenerationException, JsonMappingException, IOException {
      23. A a = new A()
      24. ObjectMapper mapper = new ObjectMapper()
      25. String temp = mapper.writeValueAsString(a)
      26. System.out.println(temp)
      27. }
      28. }
      29. class B {}

      Positive Reactions
      1. The method read works only if the List** b is empty..**
      2. I have change something in my Class A and the method save go.
      3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
      Negative Reactions
      1. Now i have another problem..
      Other Reactions
      1. I have substitute List** b new List**() with List** new ArrayList**().
      2. Are you using Eclipse?
      3. Meaning you do not have the appropriate jar file in your classpath.
      4. Why??
      5. The same function called in two activities..********
      6. See updated answer.
      7. If you copied my complete example and it did not run, then its a build path issue.
      8. Also, make sure you have get/set methods for each field in Class B.
      9. @user2520969 Did the example help?

    3. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    4. Pretty print JSON output in JBoss RESTful service

      I have a bit of a round about solution that prints it pretty decently. Not the best Pretty Print but it is enough You'll need the following from Maven Then you can change your method to something like this Since what it does is 1. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.JsonGenerationException
      2. import org.codehaus.jackson.map.JsonMappingException
      3. import org.codehaus.jackson.map.ObjectMapper
      4. import org.codehaus.jackson.map.ObjectWriter
      5. ...private final ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter()
      6. ...@GET@Path("books")@Produces({ MediaType.APPLICATION_JSON })public Response getBooks() { return Response.status(Status.OK).entity(WRITER.writeValueAsString(doGetBooks())).build()
      7. }

    5. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

  25. propertyaccessor
      Chart will be rendered here
    1. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    2. Deserializing JSON flat object using immutable classes with Jackson

      So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
      2. import com.fasterxml.jackson.annotation.JsonUnwrapped
      3. import com.fasterxml.jackson.annotation.PropertyAccessor
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
      6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
      7. A a = new A(new Foo("some_value"), "some_other_value")
      8. System.out.println(mapper.writeValueAsString(a))
      9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
      10. System.out.println(mapper.writeValueAsString(aCopy))
      11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
      12. Foo(String var1) {this.var1 = var1
      13. } private Foo() {this.var1 = null
      14. }}class A{ @JsonUnwrapped private final Foo foo
      15. private final String var2
      16. A(Foo foo, String var2) { this.foo = foo
      17. this.var2 = var2
      18. } private A() { this.foo = null
      19. this.var2 = null
      20. }}

      Positive Reactions
      1. Your solution is probably the only working in this situation.
      2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
      3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
      Other Reactions
      1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

  26. jsonautodetect
      Chart will be rendered here
    1. JSON - Check if an array exists

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.List
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2")
      10. OtherThing otherThing = target.get(0)
      11. System.out.println(otherThing.element1)
      12. // value1 System.out.println(otherThing.element2)
      13. // value2 System.out.println(otherThing.element3)
      14. // value3 } // else do something } // else do something }}class Thing{ Map<String, List<OtherThing>> objects
      15. }class OtherThing{ String element1
      16. String element2
      17. String element3
      18. }

    2. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    3. Deserializing JSON flat object using immutable classes with Jackson

      So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
      2. import com.fasterxml.jackson.annotation.JsonUnwrapped
      3. import com.fasterxml.jackson.annotation.PropertyAccessor
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
      6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
      7. A a = new A(new Foo("some_value"), "some_other_value")
      8. System.out.println(mapper.writeValueAsString(a))
      9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
      10. System.out.println(mapper.writeValueAsString(aCopy))
      11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
      12. Foo(String var1) {this.var1 = var1
      13. } private Foo() {this.var1 = null
      14. }}class A{ @JsonUnwrapped private final Foo foo
      15. private final String var2
      16. A(Foo foo, String var2) { this.foo = foo
      17. this.var2 = var2
      18. } private A() { this.foo = null
      19. this.var2 = null
      20. }}

      Positive Reactions
      1. Your solution is probably the only working in this situation.
      2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
      3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
      Other Reactions
      1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

    4. Jackson Serialization issue with CommonsMultipartFile

      By default Jackson skips all transient fields during serialization. If there is a getter for the transient field however then by default Jackson includes it during serialization. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left"} // transient fields are skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. }class CommonsMultipartFile{ private String name = "Fred"
      13. }

    5. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    6. Jackson Serialization issue with CommonsMultipartFile

      If there is a getter for the transient field however then by default Jackson includes it during serialization. One configuration option to skip the getter is to just apply the JsonIgnore annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left","fileData":{"name":"Fred"}} // transient fields with getters are not skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. public CommonsMultipartFile getFileData() {return fileData
      13. }}class CommonsMultipartFile{ private String name = "Fred"
      14. }

    7. Jackson Serialization issue with CommonsMultipartFile

      Another approach is to mark the type to be skipped with JsonIgnoreType. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnoreType
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // Types marked with @JsonIgnoreType are ignored during serialization. }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. public CommonsMultipartFile getFileData() {return fileData
      14. }}@JsonIgnoreTypeclass CommonsMultipartFile{ private String name = "Fred"
      15. }

    8. Jackson Serialization issue with CommonsMultipartFile

      If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. Another approach is to mark the type to be skipped with JsonIgnoreType. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. mapper.getSerializationConfig().addMixInAnnotations(Placement.class, SkipFileDataMixIn.class)
      8. System.out.println(mapper.writeValueAsString(new Placement()))
      9. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}abstract class SkipFileDataMixIn{ @JsonIgnore public abstract CommonsMultipartFile getFileData()
      10. }class Placement implements Serializable{ private static final long serialVersionUID = 1L
      11. private long placementId = 42
      12. private String type = "OK"
      13. private String placement = "left"
      14. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      15. public CommonsMultipartFile getFileData() {return fileData
      16. }}class CommonsMultipartFile{ private String name = "Fred"
      17. }

    9. Jackson Serialization issue with CommonsMultipartFile

      One configuration option to skip the getter is to just apply the JsonIgnore annotation. If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. @JsonIgnore public CommonsMultipartFile getFileData() {return fileData
      14. }}class CommonsMultipartFile{ private String name = "Fred"
      15. }

    10. GSON/Jackson in Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonFoo {
      5. public static void main(String[] args) throws Exception {
      6. ObjectMapper mapper = new ObjectMapper()
      7. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. System.out.println(mapper.writeValueAsString(thing))
      10. }
      11. }

    11. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

  27. deserializationconfig
      Chart will be rendered here
    1. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the first problem. Here's a solution to the second problem. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      4. A a = new A()
      5. B b = new B()
      6. C c = new C()
      7. ObjectMapper mapper = new ObjectMapper()
      8. String baseJson = mapper.writeValueAsString(base)
      9. System.out.println(baseJson)
      10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      11. System.out.println(aJson)
      12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      13. System.out.println(bJson)
      14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      15. System.out.println(cJson)
      16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      17. System.out.println(baseCopy)
      18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
      20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      22. System.out.println(aCopy)
      23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      24. System.out.println(bCopy)
      25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      26. System.out.println(cCopy)
      27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
      28. @Override public String toString() {return "baseName: " + baseName
      29. }}class A extends BaseClass{ public String aName = "a name"
      30. @Override public String toString() {return super.toString() + ", aName: " + aName
      31. }}class B extends BaseClass{ public String bName = "b name"
      32. @Override public String toString() {return super.toString() + ", bName: " + bName
      33. }}class C extends BaseClass{ public String cName = "c name"
      34. @Override public String toString() {return super.toString() + ", cName: " + cName
      35. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

  28. arraylist
      Chart will be rendered here
    1. Strict JSON parsing with Google's Gson?

      Here's an example with Jackson. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. // output: // Validating jsonInput1...// Validating jsonInput2...// Validating jsonInput3...// $.element2: is missing and it is not optional// [MyObject: element1=value1, element2=value2, element3=value3]// [MyObject: element1=value1, element2=value2, element3=null]// [MyObject: element1=value1, element2=null, element3=value3]import java.util.List
      2. import eu.vahlas.json.schema.JSONSchema
      3. import eu.vahlas.json.schema.JSONSchemaProvider
      4. import eu.vahlas.json.schema.impl.JacksonSchemaProvider
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo {
      7. static String jsonSchema =
      8. "{"
      9. + "\"description\":\"Serialized MyObject Specification\","
      10. + "\"type\":[\"object\"],"
      11. + "\"properties\":"
      12. + "{"
      13. + "\"element1\":{\"type\":\"string\"},"
      14. + "\"element2\":{\"type\":\"string\",\"optional\":false},"
      15. + "\"element3\":{\"type\":\"string\",\"optional\":true}"
      16. + "}"
      17. + "}"
      18. static String jsonInput1 =
      19. "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}"
      20. static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}"
      21. static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}"
      22. public static void main(String[] args) throws Exception {
      23. ObjectMapper mapper = new ObjectMapper()
      24. JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper)
      25. JSONSchema schema = schemaProvider.getSchema(jsonSchema)
      26. System.out.println("Validating jsonInput1...")
      27. validateAndLogErrors(jsonInput1, schema)
      28. System.out.println("Validating jsonInput2...")
      29. validateAndLogErrors(jsonInput2, schema)
      30. System.out.println("Validating jsonInput3...")
      31. validateAndLogErrors(jsonInput3, schema)
      32. MyObject object1 = mapper.readValue(jsonInput1, MyObject.class)
      33. System.out.println(object1)
      34. MyObject object2 = mapper.readValue(jsonInput2, MyObject.class)
      35. System.out.println(object2)
      36. MyObject object3 = mapper.readValue(jsonInput3, MyObject.class)
      37. System.out.println(object3)
      38. }
      39. static void validateAndLogErrors(String jsonInput, JSONSchema schema) {
      40. List<String> errors = schema.validate(jsonInput)
      41. for (String error : errors) {
      42. System.out.println(error)
      43. }
      44. }
      45. }
      46. class MyObject {
      47. String element1
      48. String element2
      49. String element3
      50. void setElement1(String element1) {
      51. this.element1 = element1
      52. }
      53. void setElement2(String element2) {
      54. this.element2 = element2
      55. }
      56. void setElement3(String element3) {
      57. this.element3 = element3
      58. }
      59. @Override
      60. public String toString() {
      61. return String.format(
      62. "[MyObject: element1=%s, element2=%s, element3=%s]", element1, element2, element3)
      63. }
      64. }

      Positive Reactions
      1. Although your proposed gson solution works when you create the type by another gson instance, it does not work when reusing the same context.
      Negative Reactions
      1. By creating a new gson you lose other configuration options your original gson had.
      Other Reactions
      1. It causes an infinite loop.

    2. need to JSON output?

      Following is a demo of Jackson in action to solve the problem originally presented. The JSON output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonDemo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. List<ProductFromServiceTemp> products = getListFromWebservice()
      6. String json = mapper.writeValueAsString(products)
      7. System.out.println(json)
      8. } private static List<ProductFromServiceTemp> getListFromWebservice() { List<ProductFromServiceTemp> productList = new ArrayList<ProductFromServiceTemp>()
      9. for (int i = 0
      10. i < 10
      11. i++) { ProductFromServiceTemp product = new ProductFromServiceTemp()
      12. product.setName("name " + i)
      13. product.setDescription("desc " + i)
      14. product.setPrice(i * 100d)
      15. productList.add(product)
      16. } return productList
      17. }}class ProductFromServiceTemp{ private String name
      18. private String description
      19. private double price
      20. // Don't use double type for financial information. public String getName() {return name
      21. } public void setName(String name) {this.name = name
      22. } public String getDescription() {return description
      23. } public void setDescription(String description) {this.description = description
      24. } public double getPrice() {return price
      25. } public void setPrice(double price) {this.price = price
      26. }}

    3. Jackson JSON, REST Data Binding & HashMaps problem

      The following demonstrates this point. There's some other problem in the system you're using. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.HashMap
      3. import java.util.List
      4. import java.util.Map
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. Map<String, String> requestMap = new HashMap<String, String>()
      8. requestMap.put("one", "1")
      9. requestMap.put("two", "2")
      10. System.out.println(mapper.writeValueAsString(requestMap))
      11. // output: {"two":"2","one":"1"} List<UserPermission> userPermissions = new ArrayList<UserPermission>()
      12. userPermissions.add(new UserPermissionImpl("domain1"))
      13. userPermissions.add(new UserPermissionImpl("domain2"))
      14. System.out.println(mapper.writeValueAsString(userPermissions))
      15. // output: [{"scope":"domain1"},{"scope":"domain2"}] Container container = new ContainerImpl(requestMap, userPermissions)
      16. // From an Interface-type reference, where the implementation is an object with two Interface-type references: System.out.println(mapper.writeValueAsString(container))
      17. // {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]} }}interface UserPermission {}class UserPermissionImpl implements UserPermission{ public String scope
      18. UserPermissionImpl(String scope) { this.scope = scope
      19. }}interface Container {}class ContainerImpl implements Container{ public Map<String, String> requestMap
      20. public List<UserPermission> userPermissions
      21. ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions) { this.requestMap = requestMap
      22. this.userPermissions = userPermissions
      23. }}

      Positive Reactions
      1. That maybe correct.
      2. If you do ever happen to figure out what's going on, do please post an update.
      3. Spring and Jersey add funny things to JSON handling.
      Other Reactions
      1. I'm sure I'm not the only curious one.
      2. There are a few things that require special configurations in order to get default Jackson behavior.
      3. :-).
      4. I'm not really sure, this thread is a few months old and I've shifted projects so I can't test it on that code base, but I'll play around when I have time.

    4. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    5. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

    6. Binding the nested json to @RequestBody object using Jackson converter

      Following is an example of using Jackson to deserialize a corrected version of the JSON into the same Parent/Child class structure in the current version of the question. Is it possible that the message about the syntax error is just that a message about a syntax error. details

      Reactions - Positive 2, Negative 1, Others 0

      1. import java.util.ArrayList
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception {/*{ "name": "foo", "age": "45", "children": [ { "name": "bar", "age": "15" }, { "name": "baz", "age": "10" } ]} */ String jsonInput = "{\"name\":\"foo\",\"age\":\"45\",\"children\":[{\"name\":\"bar\",\"age\":\"15\"},{\"name\":\"baz\",\"age\":\"10\"}]}"
      4. ObjectMapper mapper = new ObjectMapper()
      5. Parent parent = mapper.readValue(jsonInput, Parent.class)
      6. System.out.println(mapper.writeValueAsString(parent))
      7. // output: // {"name":"foo","age":45,"children":[{"name":"bar","age":15},{"name":"baz","age":10}]} }}class Parent{ public String name
      8. public int age
      9. public ArrayList<Child> children = new ArrayList<Child>()
      10. }class Child{ public String name
      11. public int age
      12. }

      Positive Reactions
      1. It's working now.
      2. Thanks for the help guys...
      Negative Reactions
      1. I figured out a problem for some reason the rest-client that I was using was making the things worse.
      Other Reactions
      1. It was the issue with the input json.
      2. Not the application itself.

  29. contextannotation
      Chart will be rendered here
    1. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  30. jsongenerator
      Chart will be rendered here
    1. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    2. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    3. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    4. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    5. How do I serialize an associated object differently using Jackson and annotations?

      The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class CustomSerializer extends JsonSerializer<Object> {
      2. private Class<?>[] _activeViews
      3. public CustomSerializer(Class<?>[] view) {
      4. _activeViews = view
      5. }
      6. @Override
      7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
      8. throws IOException, JsonProcessingException {
      9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
      10. if (filter instanceof CustomFilter) {
      11. CustomFilter customFilter = (CustomFilter) filter
      12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
      13. provider.defaultSerializeValue(value, jgen)
      14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
      15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
      16. }
      17. }
      18. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    6. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

    7. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  31. ioexception
      Chart will be rendered here
    1. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    2. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    3. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    4. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    5. Jackson Library JSON Mapper to String

      Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import java.io.IOException
      2. import java.util.List
      3. import org.codehaus.jackson.JsonGenerationException
      4. import org.codehaus.jackson.map.JsonMappingException
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class A {
      7. private List<B> b
      8. private int c
      9. public List<B> getB() {
      10. return b
      11. }
      12. public void setB(List<B> b) {
      13. this.b = b
      14. }
      15. public int getC() {
      16. return c
      17. }
      18. public void setC(int c) {
      19. this.c = c
      20. }
      21. public static void main(String[] args)
      22. throws JsonGenerationException, JsonMappingException, IOException {
      23. A a = new A()
      24. ObjectMapper mapper = new ObjectMapper()
      25. String temp = mapper.writeValueAsString(a)
      26. System.out.println(temp)
      27. }
      28. }
      29. class B {}

      Positive Reactions
      1. The method read works only if the List** b is empty..**
      2. I have change something in my Class A and the method save go.
      3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
      Negative Reactions
      1. Now i have another problem..
      Other Reactions
      1. I have substitute List** b new List**() with List** new ArrayList**().
      2. Are you using Eclipse?
      3. Meaning you do not have the appropriate jar file in your classpath.
      4. Why??
      5. The same function called in two activities..********
      6. See updated answer.
      7. If you copied my complete example and it did not run, then its a build path issue.
      8. Also, make sure you have get/set methods for each field in Class B.
      9. @user2520969 Did the example help?

    6. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    7. How do I serialize an associated object differently using Jackson and annotations?

      The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class CustomSerializer extends JsonSerializer<Object> {
      2. private Class<?>[] _activeViews
      3. public CustomSerializer(Class<?>[] view) {
      4. _activeViews = view
      5. }
      6. @Override
      7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
      8. throws IOException, JsonProcessingException {
      9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
      10. if (filter instanceof CustomFilter) {
      11. CustomFilter customFilter = (CustomFilter) filter
      12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
      13. provider.defaultSerializeValue(value, jgen)
      14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
      15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
      16. }
      17. }
      18. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    8. Removing a node in json in Java

      obsessiveCookie You're welcome and good luck!. This solution uses pure Jackson by setting the rootName on the ObjectReader . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.JsonProcessingException
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.ObjectReader
      4. import java.io.IOException
      5. public class User {
      6. public static void main(String[] args) throws JsonProcessingException, IOException {
      7. String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}"
      8. ObjectMapper mapper = new ObjectMapper()
      9. ObjectReader reader = mapper.reader(User.class).withRootName("User")
      10. User user = reader.readValue(json)
      11. System.out.println(user.getFirstname())
      12. }
      13. private String firstname
      14. private String lastname
      15. private String verified
      16. private String gender
      17. public String getFirstname() {
      18. return firstname
      19. }
      20. public void setFirstname(String firstname) {
      21. this.firstname = firstname
      22. }
      23. public String getLastname() {
      24. return lastname
      25. }
      26. public void setLastname(String lastname) {
      27. this.lastname = lastname
      28. }
      29. public String getVerified() {
      30. return verified
      31. }
      32. public void setVerified(String verified) {
      33. this.verified = verified
      34. }
      35. public String getGender() {
      36. return gender
      37. }
      38. public void setGender(String gender) {
      39. this.gender = gender
      40. }
      41. }

      Other Reactions
      1. +1 Was not aware of this alternative with jackson.

    9. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    10. Getting both JSONObject and Google Gson feature in a single library

      You can use Jackson . It has a databinding solution like Gson and a tree-model-view like JSONObject . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Main {
      4. public static class Me {
      5. public String key
      6. }
      7. public static void main(String[] args) throws IOException {
      8. ObjectMapper mapper = new ObjectMapper()
      9. String json = "{\"key\" : \"value\"}"
      10. // Feature 1 JsonNode rootNode = mapper.readValue(json, JsonNode.class)
      11. System.out.println(rootNode.get("key").getTextValue())
      12. // Feature 2 Me value = mapper.readValue(json, Me.class)
      13. System.out.println(value.key)
      14. }
      15. }

      Positive Reactions
      1. I am very happy with it :).
      2. Thanks for recommending this library.
      3. It does support sub elements.
      4. Map userData mapper.readValue(json, Map.class); it's considered as simple databinding.
      Negative Reactions
      1. Hum my bad, it seems to work with Map, List and String arrays.
      Other Reactions
      1. But...but...but... URL_http://pastebin.com/CRUH4dyG I try.
      2. No, not really, as JSon elements can have other sub elements, the JsonNode system is way better.
      3. May I know which method is better?
      4. For feature 1, is it OK for me to HashMap untyped mapper.readValue(json, HashMap.class);.
      5. Is that what you mean?

    11. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

    12. How do I parse JSON into a Map with lowercase keys using Jackson?

      Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.KeyDeserializer
      2. import org.codehaus.jackson.map.ObjectMapper
      3. import org.codehaus.jackson.map.module.SimpleModule
      4. import org.codehaus.jackson.Version
      5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
      6. }}// ...ObjectMapper mapper = new ObjectMapper()
      7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
      8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
      9. mapper.registerModule(module)
      10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

    13. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

  32. jsonprocessingexception
      Chart will be rendered here
    1. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    2. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    3. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    4. How do I serialize an associated object differently using Jackson and annotations?

      The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class CustomSerializer extends JsonSerializer<Object> {
      2. private Class<?>[] _activeViews
      3. public CustomSerializer(Class<?>[] view) {
      4. _activeViews = view
      5. }
      6. @Override
      7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
      8. throws IOException, JsonProcessingException {
      9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
      10. if (filter instanceof CustomFilter) {
      11. CustomFilter customFilter = (CustomFilter) filter
      12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
      13. provider.defaultSerializeValue(value, jgen)
      14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
      15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
      16. }
      17. }
      18. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    5. Removing a node in json in Java

      obsessiveCookie You're welcome and good luck!. This solution uses pure Jackson by setting the rootName on the ObjectReader . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.JsonProcessingException
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.ObjectReader
      4. import java.io.IOException
      5. public class User {
      6. public static void main(String[] args) throws JsonProcessingException, IOException {
      7. String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}"
      8. ObjectMapper mapper = new ObjectMapper()
      9. ObjectReader reader = mapper.reader(User.class).withRootName("User")
      10. User user = reader.readValue(json)
      11. System.out.println(user.getFirstname())
      12. }
      13. private String firstname
      14. private String lastname
      15. private String verified
      16. private String gender
      17. public String getFirstname() {
      18. return firstname
      19. }
      20. public void setFirstname(String firstname) {
      21. this.firstname = firstname
      22. }
      23. public String getLastname() {
      24. return lastname
      25. }
      26. public void setLastname(String lastname) {
      27. this.lastname = lastname
      28. }
      29. public String getVerified() {
      30. return verified
      31. }
      32. public void setVerified(String verified) {
      33. this.verified = verified
      34. }
      35. public String getGender() {
      36. return gender
      37. }
      38. public void setGender(String gender) {
      39. this.gender = gender
      40. }
      41. }

      Other Reactions
      1. +1 Was not aware of this alternative with jackson.

    6. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    7. How do I parse JSON into a Map with lowercase keys using Jackson?

      Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.KeyDeserializer
      2. import org.codehaus.jackson.map.ObjectMapper
      3. import org.codehaus.jackson.map.module.SimpleModule
      4. import org.codehaus.jackson.Version
      5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
      6. }}// ...ObjectMapper mapper = new ObjectMapper()
      7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
      8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
      9. mapper.registerModule(module)
      10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

  33. jsonproperty
      Chart will be rendered here
    1. Deserialize JSON with Jackson without proper field

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":true}"
      2. ObjectMapper mapper = new ObjectMapper()
      3. MessageWrapper wrappedMessage = mapper.readValue(inputJson, MessageWrapper.class)
      4. System.out.println(mapper.writeValueAsString(wrappedMessage))
      5. // output: {"success":true} }}class MessageWrapper{ @JsonUnwrapped @JsonProperty // exposes non-public field for Jackson use Message message
      6. }

    2. Jackson API: partially update a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class KnownPart { @JsonProperty private Customer customer
      2. @JsonProperty private BrowserInfo browser
      3. } private static class Customer { @JsonProperty private int id
      4. @JsonProperty private String name
      5. @JsonProperty private Address[] addresses
      6. // just to make it more complex for this example public Customer(int id, String name, Address[] addresses) { this.id = id
      7. this.name = name
      8. this.addresses = addresses
      9. } public Customer() { } } private static class Address { @JsonProperty private String street
      10. @JsonProperty private String city
      11. public Address(String street, String city) { this.street = street
      12. this.city = city
      13. } public Address() { } } private static class BrowserInfo { @JsonProperty private String agent
      14. @JsonProperty private String version
      15. public BrowserInfo(String agent, String version) { this.agent = agent
      16. this.version = version
      17. } public BrowserInfo() { } }

    3. How do I marshall nested key,value pairs into JSON with Camel and Jackson library?

      One way to represent this is What you'll end up with is this which although represents the data is far from ideal To get what you want use JsonAnyGetter. Something like this it could be made much easier to use) which produces I've been battling this today and your question inspired me to make it bloody work D The annotations are here annotations/wiki/Jackson-Annotations annotations/wiki/Jackson-Annotations See JUnit test here . details

      Reactions - Positive 7, Negative 1, Others 0

      1. public class Whatever {
      2. Map<String, String> keyvalues = new TreeMap<String, String>()
      3. @JsonProperty Map<String, String> visibility = new TreeMap<String, String>()
      4. @JsonAnyGetter
      5. public Map<String, String> getKeyvalues() {
      6. return keyvalues
      7. }
      8. }

      Positive Reactions
      1. I'm also using com.fasterxml.jackson.dataformat jackson-dataformat-csv 2.2.3 which seems to be importing it as well.
      2. well I hope it works for you.
      3. Thanks for the info.
      4. Please mark the answer as accepted :).
      5. Tom, thank you for the information.
      6. This test works for me.
      7. Thanks.
      Negative Reactions
      1. I discovered some Jackson library conflicts in my pom.xml that I'm cleaning up.
      Other Reactions
      1. I guess that's why its using an older version.
      2. Are you specifying that newer version in your pom.xml or your applicationContext.xml?
      3. What version Jackson are you using?
      4. I couldn't seem to get maven to pull down the fasterxml.jackson.library, so I downloaded the jackson-annotations-2.2.3.jar and added it to my classpath.
      5. Can you post your pom.xml and Camel applicationContext.xml files with your JUnit test?
      6. It now points my SensorGenerator class to the same library as yours, but I still don't get the nested visibility.
      7. Mine is imported as a dependency of restlet 2.2-M3.
      8. I added in the code you suggested, but when I run the program I only see the keyvalues in the JSON.
      9. URL_https://gist.github.com/TomDemeranville/7009250 .
      10. I looked in both and I don't seem to specify a version for the Jackson library.
      11. Btw, I looked under my .classpath under my Eclipse project and found out that yes, I am specifying multiple versions of the Jackson library, i.e.
      12. Part of my jackson is 2.1, other parts 2.2.3.
      13. I want to see if I can figure out what to add to call the newer Jackson library.
      14. here it is as a JUnit test.
      15. Here's all I've currently specified in my applicationContext.xml for marshalling to JSON: .
      16. I'm using camel-jackson 2.12.1.
      17. For some reason I don't see the nested visibility fields.
      18. I'll attach my SensorGenerator.java class, perhaps I'm missing something :-).
      19. You may have both versions on your classpath.
      20. I'm using Jackson 2.2.3 I think.
      21. Doh.
      22. The new version uses the fasterxml namespace.
      23. You are using an old version.
      24. And then further down in my .classpath I have: with a bunch of attributes set.
      25. You are using: import com.fasterxml.jackson.annotation.JsonAnyGetter;import com.fasterxml.jackson.annotation.JsonProperty; and I'm using import org.codehaus.jackson.annotate.JsonAnyGetter;import org.codehaus.jackson.annotate.JsonProperty; Did you specify the com.fasterxml library in your pom.xml?
      26. I have the following dependency in my pom.xml: org.apache.camel camel-jackson ${camel} where I define ${camel} above as 2.12.1.
      27. : .
      28. I just noticed that I'm using different libraries that you are for JsonAnyGetter and JsonProperty.

    4. How to (De)serialize field from object based on annotation using Jackson?

      I used the JsonProperty annotation instead of wrapping the functionality in the ContextualSerializer because it seemed silly to reinvent the wheel. Finally the method that performs the serialization just creates an additional ObjectMapper and registers a module in the original ObjectMapper. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import java.util.*
      2. import com.fasterxml.jackson.annotation.*
      3. public class Resource extends BaseResource{ private String name
      4. @JsonProperty("sub_resource_id") @JsonId private SubResource subResource
      5. @JsonProperty("sub_resource_ids") @JsonId private List<SubResource> subResources
      6. //getters and setters public String getName() {return name
      7. } public void setName(String name) {this.name = name
      8. } public SubResource getSubResource() {return subResource
      9. } public void setSubResource(SubResource subResource) {this.subResource = subResource
      10. } public List<SubResource> getSubResources() {return subResources
      11. } public void setSubResources(List<SubResource> subResources) {this.subResources = subResources
      12. }}

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

    5. Deserialize JSON with Jackson without proper field

      The following examples demonstrate these points. Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.annotation.JsonProperty
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      6. ObjectMapper mapper = new ObjectMapper()
      7. Message message = mapper.readValue(inputJson, Message.class)
      8. System.out.println(mapper.writeValueAsString(message))
      9. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      10. @JsonProperty("success") public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      11. } @JsonProperty("success") public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      12. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

  34. include
      Chart will be rendered here
    1. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      For example just remove the null key entries if possible before calling Jackson. That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. details

      Reactions - Positive 0, Negative 0, Others 0

      1. mapper.setSerializationInclusion(Include.NON_NULL)

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    2. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @JsonInclude(Include.NON_NULL)
      2. class Foo {
      3. public String bar
      4. Foo(String bar) {
      5. this.bar = bar
      6. }
      7. }

    3. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  35. jsonfactory
      Chart will be rendered here
    1. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    2. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

    3. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

  36. system
      Chart will be rendered here
    1. JSON - Check if an array exists

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.List
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2")
      10. OtherThing otherThing = target.get(0)
      11. System.out.println(otherThing.element1)
      12. // value1 System.out.println(otherThing.element2)
      13. // value2 System.out.println(otherThing.element3)
      14. // value3 } // else do something } // else do something }}class Thing{ Map<String, List<OtherThing>> objects
      15. }class OtherThing{ String element1
      16. String element2
      17. String element3
      18. }

    2. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    3. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    4. Jackson Library JSON Mapper to String

      Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import java.io.IOException
      2. import java.util.List
      3. import org.codehaus.jackson.JsonGenerationException
      4. import org.codehaus.jackson.map.JsonMappingException
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class A {
      7. private List<B> b
      8. private int c
      9. public List<B> getB() {
      10. return b
      11. }
      12. public void setB(List<B> b) {
      13. this.b = b
      14. }
      15. public int getC() {
      16. return c
      17. }
      18. public void setC(int c) {
      19. this.c = c
      20. }
      21. public static void main(String[] args)
      22. throws JsonGenerationException, JsonMappingException, IOException {
      23. A a = new A()
      24. ObjectMapper mapper = new ObjectMapper()
      25. String temp = mapper.writeValueAsString(a)
      26. System.out.println(temp)
      27. }
      28. }
      29. class B {}

      Positive Reactions
      1. The method read works only if the List** b is empty..**
      2. I have change something in my Class A and the method save go.
      3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
      Negative Reactions
      1. Now i have another problem..
      Other Reactions
      1. I have substitute List** b new List**() with List** new ArrayList**().
      2. Are you using Eclipse?
      3. Meaning you do not have the appropriate jar file in your classpath.
      4. Why??
      5. The same function called in two activities..********
      6. See updated answer.
      7. If you copied my complete example and it did not run, then its a build path issue.
      8. Also, make sure you have get/set methods for each field in Class B.
      9. @user2520969 Did the example help?

    5. Removing a node in json in Java

      obsessiveCookie You're welcome and good luck!. This solution uses pure Jackson by setting the rootName on the ObjectReader . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.JsonProcessingException
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.ObjectReader
      4. import java.io.IOException
      5. public class User {
      6. public static void main(String[] args) throws JsonProcessingException, IOException {
      7. String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}"
      8. ObjectMapper mapper = new ObjectMapper()
      9. ObjectReader reader = mapper.reader(User.class).withRootName("User")
      10. User user = reader.readValue(json)
      11. System.out.println(user.getFirstname())
      12. }
      13. private String firstname
      14. private String lastname
      15. private String verified
      16. private String gender
      17. public String getFirstname() {
      18. return firstname
      19. }
      20. public void setFirstname(String firstname) {
      21. this.firstname = firstname
      22. }
      23. public String getLastname() {
      24. return lastname
      25. }
      26. public void setLastname(String lastname) {
      27. this.lastname = lastname
      28. }
      29. public String getVerified() {
      30. return verified
      31. }
      32. public void setVerified(String verified) {
      33. this.verified = verified
      34. }
      35. public String getGender() {
      36. return gender
      37. }
      38. public void setGender(String gender) {
      39. this.gender = gender
      40. }
      41. }

      Other Reactions
      1. +1 Was not aware of this alternative with jackson.

    6. Jackson JSON, REST Data Binding & HashMaps problem

      The following demonstrates this point. There's some other problem in the system you're using. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.HashMap
      3. import java.util.List
      4. import java.util.Map
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. Map<String, String> requestMap = new HashMap<String, String>()
      8. requestMap.put("one", "1")
      9. requestMap.put("two", "2")
      10. System.out.println(mapper.writeValueAsString(requestMap))
      11. // output: {"two":"2","one":"1"} List<UserPermission> userPermissions = new ArrayList<UserPermission>()
      12. userPermissions.add(new UserPermissionImpl("domain1"))
      13. userPermissions.add(new UserPermissionImpl("domain2"))
      14. System.out.println(mapper.writeValueAsString(userPermissions))
      15. // output: [{"scope":"domain1"},{"scope":"domain2"}] Container container = new ContainerImpl(requestMap, userPermissions)
      16. // From an Interface-type reference, where the implementation is an object with two Interface-type references: System.out.println(mapper.writeValueAsString(container))
      17. // {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]} }}interface UserPermission {}class UserPermissionImpl implements UserPermission{ public String scope
      18. UserPermissionImpl(String scope) { this.scope = scope
      19. }}interface Container {}class ContainerImpl implements Container{ public Map<String, String> requestMap
      20. public List<UserPermission> userPermissions
      21. ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions) { this.requestMap = requestMap
      22. this.userPermissions = userPermissions
      23. }}

      Positive Reactions
      1. That maybe correct.
      2. If you do ever happen to figure out what's going on, do please post an update.
      3. Spring and Jersey add funny things to JSON handling.
      Other Reactions
      1. I'm sure I'm not the only curious one.
      2. There are a few things that require special configurations in order to get default Jackson behavior.
      3. :-).
      4. I'm not really sure, this thread is a few months old and I've shifted projects so I can't test it on that code base, but I'll play around when I have time.

    7. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    8. need to JSON output?

      Following is a demo of Jackson in action to solve the problem originally presented. The JSON output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonDemo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. List<ProductFromServiceTemp> products = getListFromWebservice()
      6. String json = mapper.writeValueAsString(products)
      7. System.out.println(json)
      8. } private static List<ProductFromServiceTemp> getListFromWebservice() { List<ProductFromServiceTemp> productList = new ArrayList<ProductFromServiceTemp>()
      9. for (int i = 0
      10. i < 10
      11. i++) { ProductFromServiceTemp product = new ProductFromServiceTemp()
      12. product.setName("name " + i)
      13. product.setDescription("desc " + i)
      14. product.setPrice(i * 100d)
      15. productList.add(product)
      16. } return productList
      17. }}class ProductFromServiceTemp{ private String name
      18. private String description
      19. private double price
      20. // Don't use double type for financial information. public String getName() {return name
      21. } public void setName(String name) {this.name = name
      22. } public String getDescription() {return description
      23. } public void setDescription(String description) {this.description = description
      24. } public double getPrice() {return price
      25. } public void setPrice(double price) {this.price = price
      26. }}

    9. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    10. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

    11. Simplest method to Convert Json to Xml

      For a simple solution I recommend Jackson as it can transform arbitrarily complex JSON into XML with just a few simple lines of code. This demo uses Jackson-1.7.7 the newer 1.7.8 should also work) xml-databind/wiki Jackson-XML-Databind-0.5.3 not yet compatible with Jackson 1.8) and Stax2-3.1.1 . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.ObjectMapper
      2. import com.fasterxml.jackson.xml.XmlMapper
      3. public class Foo{ public String name
      4. public Bar bar
      5. public static void main(String[] args) throws Exception { // JSON input: {"name":"FOO","bar":{"id":42}} String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}"
      6. ObjectMapper jsonMapper = new ObjectMapper()
      7. Foo foo = jsonMapper.readValue(jsonInput, Foo.class)
      8. XmlMapper xmlMapper = new XmlMapper()
      9. System.out.println(xmlMapper.writeValueAsString(foo))
      10. // <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo> }}class Bar{ public int id
      11. }

    12. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

  37. objectmapper
      Chart will be rendered here
    1. Setting up JSON custom deserializer

      Is there a way to tell Jackson to always use the custom deserializer to deserialize Long without having to use JsonDeserialize(using=LongJsonDeserializer.class annotation each time. Here's a full demo application. details

      Reactions - Positive 2, Negative 0, Others 0

      1. LongJsonDeserializer deserializer = new LongJsonDeserializer()
      2. SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      3. module.addDeserializer(Long.class, deserializer)
      4. ObjectMapper mapper = new ObjectMapper()
      5. mapper.registerModule(module)

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    2. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    3. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the second problem. If instead the goal is to deserialize to a subclass type without a JSON element specifically dedicated to indicate what the subclass type is then that is also possible so long as something in the JSON can be used to decide what the subclass type should be. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import org.codehaus.jackson.annotate.JsonSubTypes
      2. import org.codehaus.jackson.annotate.JsonSubTypes.Type
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      6. A a = new A()
      7. B b = new B()
      8. C c = new C()
      9. ObjectMapper mapper = new ObjectMapper()
      10. String baseJson = mapper.writeValueAsString(base)
      11. System.out.println(baseJson)
      12. // {"type":"BaseClass","baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      13. System.out.println(aJson)
      14. // {"type":"a","baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      15. System.out.println(bJson)
      16. // {"type":"b","baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      17. System.out.println(cJson)
      18. // {"type":"c","baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      19. System.out.println(baseCopy)
      20. // baseName: base name BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      21. System.out.println(aCopy)
      22. // baseName: base name, aName: a name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      23. System.out.println(bCopy)
      24. // baseName: base name, bName: b name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      25. System.out.println(cCopy)
      26. // baseName: base name, cName: c name }}@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = A.class, name = "a"), @Type(value = B.class, name = "b"), @Type(value = C.class, name = "c") }) class BaseClass{ public String baseName = "base name"
      27. @Override public String toString() {return "baseName: " + baseName
      28. }}class A extends BaseClass{ public String aName = "a name"
      29. @Override public String toString() {return super.toString() + ", aName: " + aName
      30. }}class B extends BaseClass{ public String bName = "b name"
      31. @Override public String toString() {return super.toString() + ", bName: " + bName
      32. }}class C extends BaseClass{ public String cName = "c name"
      33. @Override public String toString() {return super.toString() + ", cName: " + cName
      34. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    4. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the first problem. Here's a solution to the second problem. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      4. A a = new A()
      5. B b = new B()
      6. C c = new C()
      7. ObjectMapper mapper = new ObjectMapper()
      8. String baseJson = mapper.writeValueAsString(base)
      9. System.out.println(baseJson)
      10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      11. System.out.println(aJson)
      12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      13. System.out.println(bJson)
      14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      15. System.out.println(cJson)
      16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      17. System.out.println(baseCopy)
      18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
      20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      22. System.out.println(aCopy)
      23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      24. System.out.println(bCopy)
      25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      26. System.out.println(cCopy)
      27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
      28. @Override public String toString() {return "baseName: " + baseName
      29. }}class A extends BaseClass{ public String aName = "a name"
      30. @Override public String toString() {return super.toString() + ", aName: " + aName
      31. }}class B extends BaseClass{ public String bName = "b name"
      32. @Override public String toString() {return super.toString() + ", bName: " + bName
      33. }}class C extends BaseClass{ public String cName = "c name"
      34. @Override public String toString() {return super.toString() + ", cName: " + cName
      35. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    5. Deserializing JSON flat object using immutable classes with Jackson

      So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
      2. import com.fasterxml.jackson.annotation.JsonUnwrapped
      3. import com.fasterxml.jackson.annotation.PropertyAccessor
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
      6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
      7. A a = new A(new Foo("some_value"), "some_other_value")
      8. System.out.println(mapper.writeValueAsString(a))
      9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
      10. System.out.println(mapper.writeValueAsString(aCopy))
      11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
      12. Foo(String var1) {this.var1 = var1
      13. } private Foo() {this.var1 = null
      14. }}class A{ @JsonUnwrapped private final Foo foo
      15. private final String var2
      16. A(Foo foo, String var2) { this.foo = foo
      17. this.var2 = var2
      18. } private A() { this.foo = null
      19. this.var2 = null
      20. }}

      Positive Reactions
      1. Your solution is probably the only working in this situation.
      2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
      3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
      Other Reactions
      1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

    6. need to JSON output?

      Following is a demo of Jackson in action to solve the problem originally presented. The JSON output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonDemo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. List<ProductFromServiceTemp> products = getListFromWebservice()
      6. String json = mapper.writeValueAsString(products)
      7. System.out.println(json)
      8. } private static List<ProductFromServiceTemp> getListFromWebservice() { List<ProductFromServiceTemp> productList = new ArrayList<ProductFromServiceTemp>()
      9. for (int i = 0
      10. i < 10
      11. i++) { ProductFromServiceTemp product = new ProductFromServiceTemp()
      12. product.setName("name " + i)
      13. product.setDescription("desc " + i)
      14. product.setPrice(i * 100d)
      15. productList.add(product)
      16. } return productList
      17. }}class ProductFromServiceTemp{ private String name
      18. private String description
      19. private double price
      20. // Don't use double type for financial information. public String getName() {return name
      21. } public void setName(String name) {this.name = name
      22. } public String getDescription() {return description
      23. } public void setDescription(String description) {this.description = description
      24. } public double getPrice() {return price
      25. } public void setPrice(double price) {this.price = price
      26. }}

    7. Getting both JSONObject and Google Gson feature in a single library

      You can use Jackson . It has a databinding solution like Gson and a tree-model-view like JSONObject . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Main {
      4. public static class Me {
      5. public String key
      6. }
      7. public static void main(String[] args) throws IOException {
      8. ObjectMapper mapper = new ObjectMapper()
      9. String json = "{\"key\" : \"value\"}"
      10. // Feature 1 JsonNode rootNode = mapper.readValue(json, JsonNode.class)
      11. System.out.println(rootNode.get("key").getTextValue())
      12. // Feature 2 Me value = mapper.readValue(json, Me.class)
      13. System.out.println(value.key)
      14. }
      15. }

      Positive Reactions
      1. I am very happy with it :).
      2. Thanks for recommending this library.
      3. It does support sub elements.
      4. Map userData mapper.readValue(json, Map.class); it's considered as simple databinding.
      Negative Reactions
      1. Hum my bad, it seems to work with Map, List and String arrays.
      Other Reactions
      1. But...but...but... URL_http://pastebin.com/CRUH4dyG I try.
      2. No, not really, as JSon elements can have other sub elements, the JsonNode system is way better.
      3. May I know which method is better?
      4. For feature 1, is it OK for me to HashMap untyped mapper.readValue(json, HashMap.class);.
      5. Is that what you mean?

    8. Jackson Serialization issue with CommonsMultipartFile

      By default Jackson skips all transient fields during serialization. If there is a getter for the transient field however then by default Jackson includes it during serialization. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left"} // transient fields are skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. }class CommonsMultipartFile{ private String name = "Fred"
      13. }

    9. Jackson Serialization issue with CommonsMultipartFile

      One configuration option to skip the getter is to just apply the JsonIgnore annotation. If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. @JsonIgnore public CommonsMultipartFile getFileData() {return fileData
      14. }}class CommonsMultipartFile{ private String name = "Fred"
      15. }

    10. Jackson Serialization issue with CommonsMultipartFile

      If there is a getter for the transient field however then by default Jackson includes it during serialization. One configuration option to skip the getter is to just apply the JsonIgnore annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left","fileData":{"name":"Fred"}} // transient fields with getters are not skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. public CommonsMultipartFile getFileData() {return fileData
      13. }}class CommonsMultipartFile{ private String name = "Fred"
      14. }

    11. Jackson Serialization issue with CommonsMultipartFile

      Another approach is to mark the type to be skipped with JsonIgnoreType. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnoreType
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // Types marked with @JsonIgnoreType are ignored during serialization. }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. public CommonsMultipartFile getFileData() {return fileData
      14. }}@JsonIgnoreTypeclass CommonsMultipartFile{ private String name = "Fred"
      15. }

    12. Jackson Serialization issue with CommonsMultipartFile

      If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. Another approach is to mark the type to be skipped with JsonIgnoreType. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. mapper.getSerializationConfig().addMixInAnnotations(Placement.class, SkipFileDataMixIn.class)
      8. System.out.println(mapper.writeValueAsString(new Placement()))
      9. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}abstract class SkipFileDataMixIn{ @JsonIgnore public abstract CommonsMultipartFile getFileData()
      10. }class Placement implements Serializable{ private static final long serialVersionUID = 1L
      11. private long placementId = 42
      12. private String type = "OK"
      13. private String placement = "left"
      14. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      15. public CommonsMultipartFile getFileData() {return fileData
      16. }}class CommonsMultipartFile{ private String name = "Fred"
      17. }

    13. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    14. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

    15. Binding the nested json to @RequestBody object using Jackson converter

      Following is an example of using Jackson to deserialize a corrected version of the JSON into the same Parent/Child class structure in the current version of the question. Is it possible that the message about the syntax error is just that a message about a syntax error. details

      Reactions - Positive 2, Negative 1, Others 0

      1. import java.util.ArrayList
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception {/*{ "name": "foo", "age": "45", "children": [ { "name": "bar", "age": "15" }, { "name": "baz", "age": "10" } ]} */ String jsonInput = "{\"name\":\"foo\",\"age\":\"45\",\"children\":[{\"name\":\"bar\",\"age\":\"15\"},{\"name\":\"baz\",\"age\":\"10\"}]}"
      4. ObjectMapper mapper = new ObjectMapper()
      5. Parent parent = mapper.readValue(jsonInput, Parent.class)
      6. System.out.println(mapper.writeValueAsString(parent))
      7. // output: // {"name":"foo","age":45,"children":[{"name":"bar","age":15},{"name":"baz","age":10}]} }}class Parent{ public String name
      8. public int age
      9. public ArrayList<Child> children = new ArrayList<Child>()
      10. }class Child{ public String name
      11. public int age
      12. }

      Positive Reactions
      1. It's working now.
      2. Thanks for the help guys...
      Negative Reactions
      1. I figured out a problem for some reason the rest-client that I was using was making the things worse.
      Other Reactions
      1. It was the issue with the input json.
      2. Not the application itself.

    16. JSON - Check if an array exists

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.List
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2")
      10. OtherThing otherThing = target.get(0)
      11. System.out.println(otherThing.element1)
      12. // value1 System.out.println(otherThing.element2)
      13. // value2 System.out.println(otherThing.element3)
      14. // value3 } // else do something } // else do something }}class Thing{ Map<String, List<OtherThing>> objects
      15. }class OtherThing{ String element1
      16. String element2
      17. String element3
      18. }

    17. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    18. How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

      That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonInclude.Include
      2. import com.fasterxml.jackson.databind.SerializationFeature
      3. import java.util.HashMap
      4. import java.util.Map
      5. public class JacksonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Foo> foos = new HashMap<String, Foo>()
      8. foos.put("foo1", new Foo("foo1"))
      9. foos.put("foo2", new Foo(null))
      10. foos.put("foo3", null)
      11. foos.put(null, new Foo("foo4"))
      12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
      13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
      14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
      15. mapper.setSerializationInclusion(Include.NON_NULL)
      16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
      17. System.out.println(mapper.writeValueAsString(foos))
      18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
      19. }
      20. }
      21. class Foo {
      22. public String bar
      23. Foo(String bar) {
      24. this.bar = bar
      25. }
      26. }

      Other Reactions
      1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

    19. Jackson Library JSON Mapper to String

      Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import java.io.IOException
      2. import java.util.List
      3. import org.codehaus.jackson.JsonGenerationException
      4. import org.codehaus.jackson.map.JsonMappingException
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class A {
      7. private List<B> b
      8. private int c
      9. public List<B> getB() {
      10. return b
      11. }
      12. public void setB(List<B> b) {
      13. this.b = b
      14. }
      15. public int getC() {
      16. return c
      17. }
      18. public void setC(int c) {
      19. this.c = c
      20. }
      21. public static void main(String[] args)
      22. throws JsonGenerationException, JsonMappingException, IOException {
      23. A a = new A()
      24. ObjectMapper mapper = new ObjectMapper()
      25. String temp = mapper.writeValueAsString(a)
      26. System.out.println(temp)
      27. }
      28. }
      29. class B {}

      Positive Reactions
      1. The method read works only if the List** b is empty..**
      2. I have change something in my Class A and the method save go.
      3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
      Negative Reactions
      1. Now i have another problem..
      Other Reactions
      1. I have substitute List** b new List**() with List** new ArrayList**().
      2. Are you using Eclipse?
      3. Meaning you do not have the appropriate jar file in your classpath.
      4. Why??
      5. The same function called in two activities..********
      6. See updated answer.
      7. If you copied my complete example and it did not run, then its a build path issue.
      8. Also, make sure you have get/set methods for each field in Class B.
      9. @user2520969 Did the example help?

    20. Removing a node in json in Java

      obsessiveCookie You're welcome and good luck!. This solution uses pure Jackson by setting the rootName on the ObjectReader . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.JsonProcessingException
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.ObjectReader
      4. import java.io.IOException
      5. public class User {
      6. public static void main(String[] args) throws JsonProcessingException, IOException {
      7. String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}"
      8. ObjectMapper mapper = new ObjectMapper()
      9. ObjectReader reader = mapper.reader(User.class).withRootName("User")
      10. User user = reader.readValue(json)
      11. System.out.println(user.getFirstname())
      12. }
      13. private String firstname
      14. private String lastname
      15. private String verified
      16. private String gender
      17. public String getFirstname() {
      18. return firstname
      19. }
      20. public void setFirstname(String firstname) {
      21. this.firstname = firstname
      22. }
      23. public String getLastname() {
      24. return lastname
      25. }
      26. public void setLastname(String lastname) {
      27. this.lastname = lastname
      28. }
      29. public String getVerified() {
      30. return verified
      31. }
      32. public void setVerified(String verified) {
      33. this.verified = verified
      34. }
      35. public String getGender() {
      36. return gender
      37. }
      38. public void setGender(String gender) {
      39. this.gender = gender
      40. }
      41. }

      Other Reactions
      1. +1 Was not aware of this alternative with jackson.

    21. Jackson JSON, REST Data Binding & HashMaps problem

      The following demonstrates this point. There's some other problem in the system you're using. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.HashMap
      3. import java.util.List
      4. import java.util.Map
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. Map<String, String> requestMap = new HashMap<String, String>()
      8. requestMap.put("one", "1")
      9. requestMap.put("two", "2")
      10. System.out.println(mapper.writeValueAsString(requestMap))
      11. // output: {"two":"2","one":"1"} List<UserPermission> userPermissions = new ArrayList<UserPermission>()
      12. userPermissions.add(new UserPermissionImpl("domain1"))
      13. userPermissions.add(new UserPermissionImpl("domain2"))
      14. System.out.println(mapper.writeValueAsString(userPermissions))
      15. // output: [{"scope":"domain1"},{"scope":"domain2"}] Container container = new ContainerImpl(requestMap, userPermissions)
      16. // From an Interface-type reference, where the implementation is an object with two Interface-type references: System.out.println(mapper.writeValueAsString(container))
      17. // {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]} }}interface UserPermission {}class UserPermissionImpl implements UserPermission{ public String scope
      18. UserPermissionImpl(String scope) { this.scope = scope
      19. }}interface Container {}class ContainerImpl implements Container{ public Map<String, String> requestMap
      20. public List<UserPermission> userPermissions
      21. ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions) { this.requestMap = requestMap
      22. this.userPermissions = userPermissions
      23. }}

      Positive Reactions
      1. That maybe correct.
      2. If you do ever happen to figure out what's going on, do please post an update.
      3. Spring and Jersey add funny things to JSON handling.
      Other Reactions
      1. I'm sure I'm not the only curious one.
      2. There are a few things that require special configurations in order to get default Jackson behavior.
      3. :-).
      4. I'm not really sure, this thread is a few months old and I've shifted projects so I can't test it on that code base, but I'll play around when I have time.

    22. How do I parse JSON into a Map with lowercase keys using Jackson?

      Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.KeyDeserializer
      2. import org.codehaus.jackson.map.ObjectMapper
      3. import org.codehaus.jackson.map.module.SimpleModule
      4. import org.codehaus.jackson.Version
      5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
      6. }}// ...ObjectMapper mapper = new ObjectMapper()
      7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
      8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
      9. mapper.registerModule(module)
      10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

    23. GSON/Jackson in Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonFoo {
      5. public static void main(String[] args) throws Exception {
      6. ObjectMapper mapper = new ObjectMapper()
      7. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. System.out.println(mapper.writeValueAsString(thing))
      10. }
      11. }

    24. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

    25. Deserialize JSON with Jackson without proper field

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":true}"
      2. ObjectMapper mapper = new ObjectMapper()
      3. MessageWrapper wrappedMessage = mapper.readValue(inputJson, MessageWrapper.class)
      4. System.out.println(mapper.writeValueAsString(wrappedMessage))
      5. // output: {"success":true} }}class MessageWrapper{ @JsonUnwrapped @JsonProperty // exposes non-public field for Jackson use Message message
      6. }

    26. Deserialize JSON with Jackson without proper field

      The following examples demonstrate these points. Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.annotation.JsonProperty
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      6. ObjectMapper mapper = new ObjectMapper()
      7. Message message = mapper.readValue(inputJson, Message.class)
      8. System.out.println(mapper.writeValueAsString(message))
      9. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      10. @JsonProperty("success") public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      11. } @JsonProperty("success") public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      12. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

    27. Deserialize JSON with Jackson without proper field

      Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. Example with MessageWrapper . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      5. ObjectMapper mapper = new ObjectMapper()
      6. Message message = mapper.readValue(inputJson, Message.class)
      7. System.out.println(mapper.writeValueAsString(message))
      8. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      9. public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      10. } public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      11. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

    28. Convert JSON from URL to JSONNode

      Thanks again. I see no reason why you'd need to use a Map<String Object when Jackson has the almighty JsonNode See the databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html javadoc for-JsonNode . details

      Reactions - Positive 5, Negative 1, Others 0

      1. final JsonNode node = new ObjectMapper().readTree(new URL("yourURLHere")

      Positive Reactions
      1. I will update them later, and hope that that solves the issue.
      2. OK, compiled successfully, many thanks.
      3. Update to the latest (2.2.x) ;).
      4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
      5. Please show the dependencies you have.
      Negative Reactions
      1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
      Other Reactions
      1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
      2. I changed it to:.
      3. There you are, as you can see some them are older than that.
      4. It does work; if it doesn't, it means you use an old version of jackson- databind.
      5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
      6. I've now altered the code.

    29. Deserializing JSON into object with overloaded methods using Jackson

      input.json "value":"forty-two" Foo.java If you don't want to alter the pristine POJO defs with a Jackson annotation then you can use a MixIn. . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonIgnore
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo {
      5. String value
      6. public String getValue() {
      7. return value
      8. }
      9. public void setValue(String value) {
      10. this.value = value
      11. }
      12. public void setValue(int value) {
      13. this.value = String.valueOf(value)
      14. }
      15. public static void main(String[] args) throws Exception {
      16. ObjectMapper mapper = new ObjectMapper()
      17. mapper
      18. .getDeserializationConfig()
      19. .addMixInAnnotations(Foo.class, IgnoreFooSetValueIntMixIn.class)
      20. Foo foo = mapper.readValue(new File("input.json"), Foo.class)
      21. System.out.println(mapper.writeValueAsString(foo))
      22. }
      23. }
      24. abstract class IgnoreFooSetValueIntMixIn {
      25. @JsonIgnore
      26. public abstract void setValue(int value)
      27. }

      Positive Reactions
      1. Jackson's Mix-In facility may well suit your needs.
      2. This solution seems to be ignoring both setValue properties (i.e., nothing gets set even though the JSON contains a value).
      3. Thanks, this is exactly what I was looking for.
      4. Turns out you do need the @JsonProperty("value") on the one you want to keep.
      Negative Reactions
      1. as of jackson 1.9, this solution no longer works.
      Other Reactions
      1. Is there a method for that?
      2. It allows you to effectively annotate third party type definitions, without altering the originals.
      3. @JsonIgnore on any setter / getter / associated field applies the same to the property.
      4. What about when you cannot alter the class, when it's third party?

    30. Mapping JSON data to Java objects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.net.*
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Movie {
      5. public static void main(String[] args) throws Exception {
      6. MovieResponse response
      7. ObjectMapper mapper = new ObjectMapper()
      8. response = mapper.readValue(new File("C:\\M.json"), MovieResponse.class)
      9. System.out.println(response)
      10. }
      11. }

    31. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    32. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    33. Deserializing JSON into object with overloaded methods using Jackson

      Here's a simple example to demonstrate this point. input.json "value":"forty-two" Foo.java If you don't want to alter the pristine POJO defs with a Jackson annotation then you can use a MixIn. details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonIgnore
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo {
      5. String value
      6. public String getValue() {
      7. return value
      8. }
      9. public void setValue(String value) {
      10. this.value = value
      11. }
      12. @JsonIgnore
      13. public void setValue(int value) {
      14. this.value = String.valueOf(value)
      15. }
      16. public static void main(String[] args) throws Exception {
      17. ObjectMapper mapper = new ObjectMapper()
      18. Foo foo = mapper.readValue(new File("input.json"), Foo.class)
      19. System.out.println(mapper.writeValueAsString(foo))
      20. }
      21. }

      Positive Reactions
      1. Jackson's Mix-In facility may well suit your needs.
      2. This solution seems to be ignoring both setValue properties (i.e., nothing gets set even though the JSON contains a value).
      3. Thanks, this is exactly what I was looking for.
      4. Turns out you do need the @JsonProperty("value") on the one you want to keep.
      Negative Reactions
      1. as of jackson 1.9, this solution no longer works.
      Other Reactions
      1. Is there a method for that?
      2. It allows you to effectively annotate third party type definitions, without altering the originals.
      3. @JsonIgnore on any setter / getter / associated field applies the same to the property.
      4. What about when you cannot alter the class, when it's third party?

    34. Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

      But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.io.IOException
      3. import org.codehaus.jackson.JsonEncoding
      4. import org.codehaus.jackson.JsonFactory
      5. import org.codehaus.jackson.JsonGenerationException
      6. import org.codehaus.jackson.JsonGenerator
      7. import org.codehaus.jackson.JsonParseException
      8. import org.codehaus.jackson.map.JsonMappingException
      9. import org.codehaus.jackson.map.ObjectMapper
      10. class User { public enum Gender { MALE, FEMALE }
      11. public static class Name { private String _first, _last
      12. public String getFirst() { return _first
      13. } public String getLast() { return _last
      14. } public void setFirst(String s) { _first = s
      15. } public void setLast(String s) { _last = s
      16. } } private Gender _gender
      17. private Name _name
      18. private boolean _isVerified
      19. private byte[] _userImage
      20. public Name getName() { return _name
      21. } public boolean isVerified() { return _isVerified
      22. } public Gender getGender() { return _gender
      23. } public byte[] getUserImage() { return _userImage
      24. } public void setName(Name n) { _name = n
      25. } public void setVerified(boolean b) { _isVerified = b
      26. } public void setGender(Gender g) { _gender = g
      27. } public void setUserImage(byte[] b) { _userImage = b
      28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
      29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
      30. System.out.println(user.getName().getFirst())
      31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
      32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
      33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      34. } }}

    35. How to (De)serialize field from object based on annotation using Jackson?

      Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.fasterxml.jackson.core.*
      2. import com.fasterxml.jackson.databind.*
      3. import com.fasterxml.jackson.databind.ser.*
      4. import java.io.*
      5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
      6. implements ContextualSerializer /*<BaseResource>*/ {
      7. private ObjectMapper mapper
      8. private boolean useJsonId
      9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
      10. this(mapper, false)
      11. }
      12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
      13. this.mapper = mapper
      14. this.useJsonId = useJsonId
      15. }
      16. @Override
      17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
      18. throws IOException {
      19. if (useJsonId) {
      20. jgen.writeString(br.getId().toString())
      21. } else {
      22. mapper.writeValue(jgen, br)
      23. }
      24. }
      25. @Override
      26. public JsonSerializer<BaseResource> createContextual(
      27. SerializerProvider config, BeanProperty property)
      28. throws
      29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
      30. if (null == property) {
      31. return new ContextualJsonIdSerializer(mapper, false)
      32. }
      33. JsonId ann = property.getAnnotation(JsonId.class)
      34. if (ann
      35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
      36. }
      37. if (ann == null) { //|| ann.length() == 0) { return this
      38. //new ContextualJsonIdSerializer(false)
      39. }
      40. return new ContextualJsonIdSerializer(mapper, true)
      41. }
      42. }

      Positive Reactions
      1. If so then could you please accept it?
      Other Reactions
      1. Did this answer the question?
      2. If not then what didn't it answer?

    36. Simplest method to Convert Json to Xml

      For a simple solution I recommend Jackson as it can transform arbitrarily complex JSON into XML with just a few simple lines of code. This demo uses Jackson-1.7.7 the newer 1.7.8 should also work) xml-databind/wiki Jackson-XML-Databind-0.5.3 not yet compatible with Jackson 1.8) and Stax2-3.1.1 . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.ObjectMapper
      2. import com.fasterxml.jackson.xml.XmlMapper
      3. public class Foo{ public String name
      4. public Bar bar
      5. public static void main(String[] args) throws Exception { // JSON input: {"name":"FOO","bar":{"id":42}} String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}"
      6. ObjectMapper jsonMapper = new ObjectMapper()
      7. Foo foo = jsonMapper.readValue(jsonInput, Foo.class)
      8. XmlMapper xmlMapper = new XmlMapper()
      9. System.out.println(xmlMapper.writeValueAsString(foo))
      10. // <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo> }}class Bar{ public int id
      11. }

    37. Strict JSON parsing with Google's Gson?

      Here's an example with Jackson. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. // output: // Validating jsonInput1...// Validating jsonInput2...// Validating jsonInput3...// $.element2: is missing and it is not optional// [MyObject: element1=value1, element2=value2, element3=value3]// [MyObject: element1=value1, element2=value2, element3=null]// [MyObject: element1=value1, element2=null, element3=value3]import java.util.List
      2. import eu.vahlas.json.schema.JSONSchema
      3. import eu.vahlas.json.schema.JSONSchemaProvider
      4. import eu.vahlas.json.schema.impl.JacksonSchemaProvider
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo {
      7. static String jsonSchema =
      8. "{"
      9. + "\"description\":\"Serialized MyObject Specification\","
      10. + "\"type\":[\"object\"],"
      11. + "\"properties\":"
      12. + "{"
      13. + "\"element1\":{\"type\":\"string\"},"
      14. + "\"element2\":{\"type\":\"string\",\"optional\":false},"
      15. + "\"element3\":{\"type\":\"string\",\"optional\":true}"
      16. + "}"
      17. + "}"
      18. static String jsonInput1 =
      19. "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}"
      20. static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}"
      21. static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}"
      22. public static void main(String[] args) throws Exception {
      23. ObjectMapper mapper = new ObjectMapper()
      24. JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper)
      25. JSONSchema schema = schemaProvider.getSchema(jsonSchema)
      26. System.out.println("Validating jsonInput1...")
      27. validateAndLogErrors(jsonInput1, schema)
      28. System.out.println("Validating jsonInput2...")
      29. validateAndLogErrors(jsonInput2, schema)
      30. System.out.println("Validating jsonInput3...")
      31. validateAndLogErrors(jsonInput3, schema)
      32. MyObject object1 = mapper.readValue(jsonInput1, MyObject.class)
      33. System.out.println(object1)
      34. MyObject object2 = mapper.readValue(jsonInput2, MyObject.class)
      35. System.out.println(object2)
      36. MyObject object3 = mapper.readValue(jsonInput3, MyObject.class)
      37. System.out.println(object3)
      38. }
      39. static void validateAndLogErrors(String jsonInput, JSONSchema schema) {
      40. List<String> errors = schema.validate(jsonInput)
      41. for (String error : errors) {
      42. System.out.println(error)
      43. }
      44. }
      45. }
      46. class MyObject {
      47. String element1
      48. String element2
      49. String element3
      50. void setElement1(String element1) {
      51. this.element1 = element1
      52. }
      53. void setElement2(String element2) {
      54. this.element2 = element2
      55. }
      56. void setElement3(String element3) {
      57. this.element3 = element3
      58. }
      59. @Override
      60. public String toString() {
      61. return String.format(
      62. "[MyObject: element1=%s, element2=%s, element3=%s]", element1, element2, element3)
      63. }
      64. }

      Positive Reactions
      1. Although your proposed gson solution works when you create the type by another gson instance, it does not work when reusing the same context.
      Negative Reactions
      1. By creating a new gson you lose other configuration options your original gson had.
      Other Reactions
      1. It causes an infinite loop.

    38. Pretty print JSON output in JBoss RESTful service

      I have a bit of a round about solution that prints it pretty decently. Not the best Pretty Print but it is enough You'll need the following from Maven Then you can change your method to something like this Since what it does is 1. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.JsonGenerationException
      2. import org.codehaus.jackson.map.JsonMappingException
      3. import org.codehaus.jackson.map.ObjectMapper
      4. import org.codehaus.jackson.map.ObjectWriter
      5. ...private final ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter()
      6. ...@GET@Path("books")@Produces({ MediaType.APPLICATION_JSON })public Response getBooks() { return Response.status(Status.OK).entity(WRITER.writeValueAsString(doGetBooks())).build()
      7. }

    39. How to use JSONDeserializer to deserialize this string?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void readValueAsMap() throws Exception{ String value = "{\"226167\":\"myshow\",\"3193\":\"yourshow\"}"
      2. ObjectMapper mapper = new ObjectMapper()
      3. Map<String,String> valueAsMap = mapper.readValue(value, Map.class)
      4. Collection<String> values = valueAsMap.keySet()
      5. assertTrue(values.contains("226167"))
      6. assertTrue(values.contains("3193"))
      7. }

  38. exception
      Chart will be rendered here
    1. Setting up JSON custom deserializer

      This works with the latest release of Jackson and probably also with Jackson versions going back to 1.7. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonParser
      3. import org.codehaus.jackson.JsonProcessingException
      4. import org.codehaus.jackson.Version
      5. import org.codehaus.jackson.map.DeserializationContext
      6. import org.codehaus.jackson.map.JsonDeserializer
      7. import org.codehaus.jackson.map.ObjectMapper
      8. import org.codehaus.jackson.map.module.SimpleModule
      9. public class Foo{ public static void main(String[] args) throws Exception { TestBean bean = new TestBean()
      10. bean.value = 42L
      11. ObjectMapper mapper = new ObjectMapper()
      12. String beanJson = mapper.writeValueAsString(bean)
      13. System.out.println(beanJson)
      14. // output: {"value":42} TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class)
      15. System.out.println(beanCopy1.value)
      16. // output: 42 SimpleModule module = new SimpleModule("LongDeserializerModule", new Version(1, 0, 0, null))
      17. module.addDeserializer(Long.class, new LongJsonDeserializer())
      18. mapper = new ObjectMapper()
      19. mapper.registerModule(module)
      20. TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class)
      21. System.out.println(beanCopy2.value)
      22. // output: 126 }}class TestBean{ Long value
      23. public Long getValue() {return value
      24. } public void setValue(Long value) {this.value = value
      25. }}class LongJsonDeserializer extends JsonDeserializer<Long>{ @Override public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Long value = jp.getLongValue()
      26. return value * 3
      27. }}

      Positive Reactions
      1. This is same as described in URL_http://wiki.fasterxml.com/JacksonHowToCustomDeserializers , which I have already followed!.
      2. I read the original question too fast, maybe.
      Other Reactions
      1. Ah.
      2. Taking another look...
      3. I'll update this post with a full demo application.
      4. What I originally posted addressed the question you asked correctly.

    2. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the second problem. If instead the goal is to deserialize to a subclass type without a JSON element specifically dedicated to indicate what the subclass type is then that is also possible so long as something in the JSON can be used to decide what the subclass type should be. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import org.codehaus.jackson.annotate.JsonSubTypes
      2. import org.codehaus.jackson.annotate.JsonSubTypes.Type
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      6. A a = new A()
      7. B b = new B()
      8. C c = new C()
      9. ObjectMapper mapper = new ObjectMapper()
      10. String baseJson = mapper.writeValueAsString(base)
      11. System.out.println(baseJson)
      12. // {"type":"BaseClass","baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      13. System.out.println(aJson)
      14. // {"type":"a","baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      15. System.out.println(bJson)
      16. // {"type":"b","baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      17. System.out.println(cJson)
      18. // {"type":"c","baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      19. System.out.println(baseCopy)
      20. // baseName: base name BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      21. System.out.println(aCopy)
      22. // baseName: base name, aName: a name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      23. System.out.println(bCopy)
      24. // baseName: base name, bName: b name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      25. System.out.println(cCopy)
      26. // baseName: base name, cName: c name }}@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = A.class, name = "a"), @Type(value = B.class, name = "b"), @Type(value = C.class, name = "c") }) class BaseClass{ public String baseName = "base name"
      27. @Override public String toString() {return "baseName: " + baseName
      28. }}class A extends BaseClass{ public String aName = "a name"
      29. @Override public String toString() {return super.toString() + ", aName: " + aName
      30. }}class B extends BaseClass{ public String bName = "b name"
      31. @Override public String toString() {return super.toString() + ", bName: " + bName
      32. }}class C extends BaseClass{ public String cName = "c name"
      33. @Override public String toString() {return super.toString() + ", cName: " + cName
      34. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    3. How do I serialize an associated object differently using Jackson and annotations?

      Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

      Reactions - Positive 7, Negative 1, Others 0

      1. public static class CustomFilter extends SimpleBeanPropertyFilter {
      2. private Class<?>[] _nextViews
      3. public void setNextViews(Class<?>[] clazz) {
      4. _nextViews = clazz
      5. }
      6. @Override
      7. public void serializeAsField(
      8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
      9. throws Exception {
      10. Class<?>[] propViews = writer.getViews()
      11. if (propViews != null && _nextViews != null) {
      12. for (Class<?> propView : propViews) {
      13. System.out.println(propView.getName())
      14. for (Class<?> currentView : _nextViews) {
      15. if (!propView.isAssignableFrom(
      16. currentView)) { // Do the filtering! return
      17. }
      18. }
      19. }
      20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
      21. }
      22. }

      Positive Reactions
      1. I think it can give a thread safe and much simpler implementation.
      2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
      3. I'll end up doing something like your example, just with some tweaks.
      4. if it not a problem, please, do the refactoring with a multithreading.
      5. However, my solution is still useful if you have a lot of properties to filter.
      6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
      7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
      Negative Reactions
      1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
      Other Reactions
      1. I have some refactoring to do now...
      2. I ended up looking at BeanSerializerModifier.class.
      3. I will look at it tomorrow morning.
      4. I had already seen that but didn't have time and forgot.
      5. @RansomBriggs Hmm, I agree.

    4. Deserializing JSON flat object using immutable classes with Jackson

      So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
      2. import com.fasterxml.jackson.annotation.JsonUnwrapped
      3. import com.fasterxml.jackson.annotation.PropertyAccessor
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
      6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
      7. A a = new A(new Foo("some_value"), "some_other_value")
      8. System.out.println(mapper.writeValueAsString(a))
      9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
      10. System.out.println(mapper.writeValueAsString(aCopy))
      11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
      12. Foo(String var1) {this.var1 = var1
      13. } private Foo() {this.var1 = null
      14. }}class A{ @JsonUnwrapped private final Foo foo
      15. private final String var2
      16. A(Foo foo, String var2) { this.foo = foo
      17. this.var2 = var2
      18. } private A() { this.foo = null
      19. this.var2 = null
      20. }}

      Positive Reactions
      1. Your solution is probably the only working in this situation.
      2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
      3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
      Other Reactions
      1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

    5. need to JSON output?

      Following is a demo of Jackson in action to solve the problem originally presented. The JSON output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonDemo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. List<ProductFromServiceTemp> products = getListFromWebservice()
      6. String json = mapper.writeValueAsString(products)
      7. System.out.println(json)
      8. } private static List<ProductFromServiceTemp> getListFromWebservice() { List<ProductFromServiceTemp> productList = new ArrayList<ProductFromServiceTemp>()
      9. for (int i = 0
      10. i < 10
      11. i++) { ProductFromServiceTemp product = new ProductFromServiceTemp()
      12. product.setName("name " + i)
      13. product.setDescription("desc " + i)
      14. product.setPrice(i * 100d)
      15. productList.add(product)
      16. } return productList
      17. }}class ProductFromServiceTemp{ private String name
      18. private String description
      19. private double price
      20. // Don't use double type for financial information. public String getName() {return name
      21. } public void setName(String name) {this.name = name
      22. } public String getDescription() {return description
      23. } public void setDescription(String description) {this.description = description
      24. } public double getPrice() {return price
      25. } public void setPrice(double price) {this.price = price
      26. }}

    6. Jackson API: partially update a string

      The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
      2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
      3. jgen.writeStartObject()
      4. serializeFields(up, jgen, provider)
      5. jgen.writeEndObject()
      6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
      7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
      8. } else { props = _props
      9. } int i = 0
      10. try { for (final int len = props.length
      11. i < len
      12. ++i) { BeanPropertyWriter prop = props[i]
      13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
      14. bean.tree.remove(prop.getName())
      15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
      16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
      17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
      18. jgen.writeFieldName(e.getKey())
      19. jgen.writeObject(e.getValue())
      20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      21. wrapAndThrow(provider, e, bean, name)
      22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
      23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
      24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
      25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
      26. throw mapE
      27. } } }

    7. Jackson Serialization issue with CommonsMultipartFile

      By default Jackson skips all transient fields during serialization. If there is a getter for the transient field however then by default Jackson includes it during serialization. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left"} // transient fields are skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. }class CommonsMultipartFile{ private String name = "Fred"
      13. }

    8. How can I polymorphic deserialization Json String using Java and Jackson Library?

      Here's a solution to the first problem. Here's a solution to the second problem. details

      Reactions - Positive 1, Negative 4, Others 0

      1. import static org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception { BaseClass base = new BaseClass()
      4. A a = new A()
      5. B b = new B()
      6. C c = new C()
      7. ObjectMapper mapper = new ObjectMapper()
      8. String baseJson = mapper.writeValueAsString(base)
      9. System.out.println(baseJson)
      10. // {"baseName":"base name"} String aJson = mapper.writeValueAsString(a)
      11. System.out.println(aJson)
      12. // {"baseName":"base name","aName":"a name"} String bJson = mapper.writeValueAsString(b)
      13. System.out.println(bJson)
      14. // {"baseName":"base name","bName":"b name"} String cJson = mapper.writeValueAsString(c)
      15. System.out.println(cJson)
      16. // {"baseName":"base name","cName":"c name"} BaseClass baseCopy = mapper.readValue(baseJson, BaseClass.class)
      17. System.out.println(baseCopy)
      18. // baseName: base name // BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      19. // throws UnrecognizedPropertyException: // Unrecognized field "aName", not marked as ignorable // because the JSON contains elements for which no Java field // to bind to was provided. // Need to let Jackson know that not all JSON elements must be bound. // To resolve this, the class can be annotated with // @JsonIgnoreProperties(ignoreUnknown=true) or the ObjectMapper can be // directly configured to not FAIL_ON_UNKNOWN_PROPERTIES mapper = new ObjectMapper()
      20. mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. BaseClass aCopy = mapper.readValue(aJson, BaseClass.class)
      22. System.out.println(aCopy)
      23. // baseName: base name BaseClass bCopy = mapper.readValue(bJson, BaseClass.class)
      24. System.out.println(bCopy)
      25. // baseName: base name BaseClass cCopy = mapper.readValue(cJson, BaseClass.class)
      26. System.out.println(cCopy)
      27. // baseName: base name }}class BaseClass{ public String baseName = "base name"
      28. @Override public String toString() {return "baseName: " + baseName
      29. }}class A extends BaseClass{ public String aName = "a name"
      30. @Override public String toString() {return super.toString() + ", aName: " + aName
      31. }}class B extends BaseClass{ public String bName = "b name"
      32. @Override public String toString() {return super.toString() + ", bName: " + bName
      33. }}class C extends BaseClass{ public String cName = "c name"
      34. @Override public String toString() {return super.toString() + ", cName: " + cName
      35. }}

      Positive Reactions
      1. Thank you!.
      Negative Reactions
      1. It's the second problem I'm concerning.
      2. I've edited the question to reflect my concern.
      3. Sorry, I wasn't clear enough.
      4. I was actually looking for a solution to problem 1 - FAIL_ON_UNKNOWN_PROPERTIES false was just what I needed :).
      Other Reactions
      1. You just hit the spot.

    9. Jackson Serialization issue with CommonsMultipartFile

      One configuration option to skip the getter is to just apply the JsonIgnore annotation. If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. @JsonIgnore public CommonsMultipartFile getFileData() {return fileData
      14. }}class CommonsMultipartFile{ private String name = "Fred"
      15. }

    10. Jackson Serialization issue with CommonsMultipartFile

      If there is a getter for the transient field however then by default Jackson includes it during serialization. One configuration option to skip the getter is to just apply the JsonIgnore annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      5. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      6. System.out.println(mapper.writeValueAsString(new Placement()))
      7. // output: {"placementId":42,"type":"OK","placement":"left","fileData":{"name":"Fred"}} // transient fields with getters are not skipped by default }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      8. private long placementId = 42
      9. private String type = "OK"
      10. private String placement = "left"
      11. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      12. public CommonsMultipartFile getFileData() {return fileData
      13. }}class CommonsMultipartFile{ private String name = "Fred"
      14. }

    11. Jackson Serialization issue with CommonsMultipartFile

      Another approach is to mark the type to be skipped with JsonIgnoreType. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnoreType
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. System.out.println(mapper.writeValueAsString(new Placement()))
      8. // output: {"placementId":42,"type":"OK","placement":"left"} // Types marked with @JsonIgnoreType are ignored during serialization. }}class Placement implements Serializable{ private static final long serialVersionUID = 1L
      9. private long placementId = 42
      10. private String type = "OK"
      11. private String placement = "left"
      12. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      13. public CommonsMultipartFile getFileData() {return fileData
      14. }}@JsonIgnoreTypeclass CommonsMultipartFile{ private String name = "Fred"
      15. }

    12. Jackson Serialization issue with CommonsMultipartFile

      If it's not possible or desirable to edit the original class definition to add the JsonIgnore annotation a Mix-In can be used. Another approach is to mark the type to be skipped with JsonIgnoreType. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.Serializable
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.annotate.JsonIgnore
      4. import org.codehaus.jackson.map.ObjectMapper
      5. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      6. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      7. mapper.getSerializationConfig().addMixInAnnotations(Placement.class, SkipFileDataMixIn.class)
      8. System.out.println(mapper.writeValueAsString(new Placement()))
      9. // output: {"placementId":42,"type":"OK","placement":"left"} // getters marked with @JsonIgnore are ignored }}abstract class SkipFileDataMixIn{ @JsonIgnore public abstract CommonsMultipartFile getFileData()
      10. }class Placement implements Serializable{ private static final long serialVersionUID = 1L
      11. private long placementId = 42
      12. private String type = "OK"
      13. private String placement = "left"
      14. private transient CommonsMultipartFile fileData = new CommonsMultipartFile()
      15. public CommonsMultipartFile getFileData() {return fileData
      16. }}class CommonsMultipartFile{ private String name = "Fred"
      17. }

    13. Flatten JSON into Specific Format

      After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. public class JacksonProgram {
      3. public static void main(String[] args) throws Exception {
      4. JsonConverter converter = new JsonConverter()
      5. String result = converter.convert(new File("/tmp/source.json"))
      6. System.out.println(result)
      7. }
      8. }

    14. Flatten JSON into Specific Format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JsonConverter {
      2. private ObjectMapper objectMapper = new ObjectMapper()
      3. private JsonFactory jsonFactory = new JsonFactory()
      4. public String convert(File sourceJsonFile) throws Exception {
      5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
      6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
      7. return objectMapper.writeValueAsString(result)
      8. }
      9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
      10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
      11. return objectMapper.readValue(parser, SourceEntity.class)
      12. }
      13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
      14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
      15. for (String[][] pairs : entity.getRecords()) {
      16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
      17. }
      18. return list
      19. }
      20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
      21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
      22. for (int i = 0 i < values.length i++) {
      23. propertyMap.put(names[i], values[i])
      24. }
      25. return propertyMap
      26. }
      27. }

    15. JSON - Check if an array exists

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.List
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2")
      10. OtherThing otherThing = target.get(0)
      11. System.out.println(otherThing.element1)
      12. // value1 System.out.println(otherThing.element2)
      13. // value2 System.out.println(otherThing.element3)
      14. // value3 } // else do something } // else do something }}class Thing{ Map<String, List<OtherThing>> objects
      15. }class OtherThing{ String element1
      16. String element2
      17. String element3
      18. }

    16. Reading multiple elements from json file

      If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

      Reactions - Positive 0, Negative 2, Others 0

      1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
      2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. import java.io.File
      5. import java.util.Iterator
      6. public class JacksonFoo {
      7. public static void main(String[] args) throws Exception {
      8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
      9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
      10. while (thingsIterator.hasNext()) {
      11. System.out.println(thingsIterator.next())
      12. }
      13. }
      14. }
      15. class Thing {
      16. private String name
      17. @Override
      18. public String toString() {
      19. return String.format("Thing: name=%s", name)
      20. }
      21. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    17. Jackson JSON, REST Data Binding & HashMaps problem

      The following demonstrates this point. There's some other problem in the system you're using. details

      Reactions - Positive 3, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.HashMap
      3. import java.util.List
      4. import java.util.Map
      5. import org.codehaus.jackson.map.ObjectMapper
      6. public class Foo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper()
      7. Map<String, String> requestMap = new HashMap<String, String>()
      8. requestMap.put("one", "1")
      9. requestMap.put("two", "2")
      10. System.out.println(mapper.writeValueAsString(requestMap))
      11. // output: {"two":"2","one":"1"} List<UserPermission> userPermissions = new ArrayList<UserPermission>()
      12. userPermissions.add(new UserPermissionImpl("domain1"))
      13. userPermissions.add(new UserPermissionImpl("domain2"))
      14. System.out.println(mapper.writeValueAsString(userPermissions))
      15. // output: [{"scope":"domain1"},{"scope":"domain2"}] Container container = new ContainerImpl(requestMap, userPermissions)
      16. // From an Interface-type reference, where the implementation is an object with two Interface-type references: System.out.println(mapper.writeValueAsString(container))
      17. // {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]} }}interface UserPermission {}class UserPermissionImpl implements UserPermission{ public String scope
      18. UserPermissionImpl(String scope) { this.scope = scope
      19. }}interface Container {}class ContainerImpl implements Container{ public Map<String, String> requestMap
      20. public List<UserPermission> userPermissions
      21. ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions) { this.requestMap = requestMap
      22. this.userPermissions = userPermissions
      23. }}

      Positive Reactions
      1. That maybe correct.
      2. If you do ever happen to figure out what's going on, do please post an update.
      3. Spring and Jersey add funny things to JSON handling.
      Other Reactions
      1. I'm sure I'm not the only curious one.
      2. There are a few things that require special configurations in order to get default Jackson behavior.
      3. :-).
      4. I'm not really sure, this thread is a few months old and I've shifted projects so I can't test it on that code base, but I'll play around when I have time.

    18. GSON/Jackson in Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class JacksonFoo {
      5. public static void main(String[] args) throws Exception {
      6. ObjectMapper mapper = new ObjectMapper()
      7. mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY))
      8. Thing thing = mapper.readValue(new File("input.json"), Thing.class)
      9. System.out.println(mapper.writeValueAsString(thing))
      10. }
      11. }

    19. Jackson: deserialization of Map

      The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.io.File
      2. import java.util.HashMap
      3. import java.util.Map
      4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      5. import org.codehaus.jackson.annotate.JsonMethod
      6. import org.codehaus.jackson.map.ObjectMapper
      7. import org.codehaus.jackson.type.TypeReference
      8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
      9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
      10. System.out.println(cache)
      11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
      12. String filePath
      13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
      14. }}

    20. Deserialize JSON with Jackson without proper field

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":true}"
      2. ObjectMapper mapper = new ObjectMapper()
      3. MessageWrapper wrappedMessage = mapper.readValue(inputJson, MessageWrapper.class)
      4. System.out.println(mapper.writeValueAsString(wrappedMessage))
      5. // output: {"success":true} }}class MessageWrapper{ @JsonUnwrapped @JsonProperty // exposes non-public field for Jackson use Message message
      6. }

    21. Using Jackson's @JsonTypeInfo with a custom serializer

      The following additions/modifications to the test source code generate the desired output. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. private static class AnimalMap implements Map<Object, Animal> { private final Map<Object, Animal> map
      2. public AnimalMap() { super()
      3. this.map = new HashMap<Object, Animal>()
      4. } // omitting delegation of all Map<> interface methods to this.map}static class ZooSerializer extends SerializerBase<Zoo> { public ZooSerializer() { super(Zoo.class)
      5. } @Override public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception { AnimalMap animals = new AnimalMap()
      6. for (Animal a : t.animals) animals.put(a.getName(), a)
      7. jg.writeObject(animals)
      8. }}

      Positive Reactions
      1. Correct -- when sub-classing a Collection or Map, generic type information is stored in class file for super type (but NOT type itself!).
      Other Reactions
      1. This is one of possible work arounds -- another is using TypeReference / JavaType, which can express generic type signatures.

    22. Deserialize JSON with Jackson without proper field

      The following examples demonstrate these points. Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.annotation.JsonProperty
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      6. ObjectMapper mapper = new ObjectMapper()
      7. Message message = mapper.readValue(inputJson, Message.class)
      8. System.out.println(mapper.writeValueAsString(message))
      9. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      10. @JsonProperty("success") public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      11. } @JsonProperty("success") public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      12. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

    23. Deserialize JSON with Jackson without proper field

      Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. Example with MessageWrapper . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.HashMap
      2. import java.util.Map
      3. import com.fasterxml.jackson.databind.ObjectMapper
      4. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
      5. ObjectMapper mapper = new ObjectMapper()
      6. Message message = mapper.readValue(inputJson, Message.class)
      7. System.out.println(mapper.writeValueAsString(message))
      8. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
      9. public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
      10. } public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
      11. }}

      Positive Reactions
      1. Thanks for your answers.
      Negative Reactions
      1. Obviously, I have something wrong in my code.
      Other Reactions
      1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
      2. But I can't make it work.
      3. I'll update the answer above to includes such an example.
      4. -- No.
      5. That what I thought...
      6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
      7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

    24. Deserializing JSON into object with overloaded methods using Jackson

      input.json "value":"forty-two" Foo.java If you don't want to alter the pristine POJO defs with a Jackson annotation then you can use a MixIn. . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonIgnore
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo {
      5. String value
      6. public String getValue() {
      7. return value
      8. }
      9. public void setValue(String value) {
      10. this.value = value
      11. }
      12. public void setValue(int value) {
      13. this.value = String.valueOf(value)
      14. }
      15. public static void main(String[] args) throws Exception {
      16. ObjectMapper mapper = new ObjectMapper()
      17. mapper
      18. .getDeserializationConfig()
      19. .addMixInAnnotations(Foo.class, IgnoreFooSetValueIntMixIn.class)
      20. Foo foo = mapper.readValue(new File("input.json"), Foo.class)
      21. System.out.println(mapper.writeValueAsString(foo))
      22. }
      23. }
      24. abstract class IgnoreFooSetValueIntMixIn {
      25. @JsonIgnore
      26. public abstract void setValue(int value)
      27. }

      Positive Reactions
      1. Jackson's Mix-In facility may well suit your needs.
      2. This solution seems to be ignoring both setValue properties (i.e., nothing gets set even though the JSON contains a value).
      3. Thanks, this is exactly what I was looking for.
      4. Turns out you do need the @JsonProperty("value") on the one you want to keep.
      Negative Reactions
      1. as of jackson 1.9, this solution no longer works.
      Other Reactions
      1. Is there a method for that?
      2. It allows you to effectively annotate third party type definitions, without altering the originals.
      3. @JsonIgnore on any setter / getter / associated field applies the same to the property.
      4. What about when you cannot alter the class, when it's third party?

    25. How to use JSONDeserializer to deserialize this string?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void readValueAsMap() throws Exception{ String value = "{\"226167\":\"myshow\",\"3193\":\"yourshow\"}"
      2. ObjectMapper mapper = new ObjectMapper()
      3. Map<String,String> valueAsMap = mapper.readValue(value, Map.class)
      4. Collection<String> values = valueAsMap.keySet()
      5. assertTrue(values.contains("226167"))
      6. assertTrue(values.contains("3193"))
      7. }

    26. Jackson deserialize object or array

      Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

      Reactions - Positive 4, Negative 2, Others 0

      1. import java.io.IOException
      2. import org.codehaus.jackson.JsonNode
      3. import org.codehaus.jackson.JsonParser
      4. import org.codehaus.jackson.JsonProcessingException
      5. import org.codehaus.jackson.Version
      6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
      7. import org.codehaus.jackson.annotate.JsonMethod
      8. import org.codehaus.jackson.map.DeserializationContext
      9. import org.codehaus.jackson.map.JsonDeserializer
      10. import org.codehaus.jackson.map.ObjectMapper
      11. import org.codehaus.jackson.map.module.SimpleModule
      12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
      13. // {"property1":[]} String json2 = "{\"property1\":[]}"
      14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
      15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
      16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
      17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
      18. System.out.println(firstThing)
      19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
      20. System.out.println(secondThing)
      21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
      22. @Override public String toString() { return String.format("Thing1: property1=%s", property1)
      23. }}class Thing2{ int property2
      24. @Override public String toString() { return String.format("Thing2: property2=%d", property2)
      25. }}class ArrayAsNullDeserializer extends JsonDeserializer<Thing2>{ @Override public Thing2 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree()
      26. if (node.isObject()) return new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).readValue(node, Thing2.class)
      27. return null
      28. }}

      Positive Reactions
      1. Awesome job Bruce, thanks a bunch!.
      2. Do you happen to know of a good tutorial on writing one?
      3. Thanks, I kinda figured this was going to be the case...never can just be easy can it!
      4. Ok!
      Negative Reactions
      1. or, in the worst case, if that is the only case, what about a string replace from "[]" to "{}".
      2. I wish I could, it's a web service call I have no control over, from a battlefield bad company 2 website.
      Other Reactions
      1. -- Answer updated with example.
      2. no chance on fixing the original input, right?

    27. Deserializing JSON into object with overloaded methods using Jackson

      Here's a simple example to demonstrate this point. input.json "value":"forty-two" Foo.java If you don't want to alter the pristine POJO defs with a Jackson annotation then you can use a MixIn. details

      Reactions - Positive 4, Negative 1, Others 0

      1. import java.io.File
      2. import org.codehaus.jackson.annotate.JsonIgnore
      3. import org.codehaus.jackson.map.ObjectMapper
      4. public class Foo {
      5. String value
      6. public String getValue() {
      7. return value
      8. }
      9. public void setValue(String value) {
      10. this.value = value
      11. }
      12. @JsonIgnore
      13. public void setValue(int value) {
      14. this.value = String.valueOf(value)
      15. }
      16. public static void main(String[] args) throws Exception {
      17. ObjectMapper mapper = new ObjectMapper()
      18. Foo foo = mapper.readValue(new File("input.json"), Foo.class)
      19. System.out.println(mapper.writeValueAsString(foo))
      20. }
      21. }

      Positive Reactions
      1. Jackson's Mix-In facility may well suit your needs.
      2. This solution seems to be ignoring both setValue properties (i.e., nothing gets set even though the JSON contains a value).
      3. Thanks, this is exactly what I was looking for.
      4. Turns out you do need the @JsonProperty("value") on the one you want to keep.
      Negative Reactions
      1. as of jackson 1.9, this solution no longer works.
      Other Reactions
      1. Is there a method for that?
      2. It allows you to effectively annotate third party type definitions, without altering the originals.
      3. @JsonIgnore on any setter / getter / associated field applies the same to the property.
      4. What about when you cannot alter the class, when it's third party?

    28. Binding the nested json to @RequestBody object using Jackson converter

      Following is an example of using Jackson to deserialize a corrected version of the JSON into the same Parent/Child class structure in the current version of the question. Is it possible that the message about the syntax error is just that a message about a syntax error. details

      Reactions - Positive 2, Negative 1, Others 0

      1. import java.util.ArrayList
      2. import org.codehaus.jackson.map.ObjectMapper
      3. public class Foo{ public static void main(String[] args) throws Exception {/*{ "name": "foo", "age": "45", "children": [ { "name": "bar", "age": "15" }, { "name": "baz", "age": "10" } ]} */ String jsonInput = "{\"name\":\"foo\",\"age\":\"45\",\"children\":[{\"name\":\"bar\",\"age\":\"15\"},{\"name\":\"baz\",\"age\":\"10\"}]}"
      4. ObjectMapper mapper = new ObjectMapper()
      5. Parent parent = mapper.readValue(jsonInput, Parent.class)
      6. System.out.println(mapper.writeValueAsString(parent))
      7. // output: // {"name":"foo","age":45,"children":[{"name":"bar","age":15},{"name":"baz","age":10}]} }}class Parent{ public String name
      8. public int age
      9. public ArrayList<Child> children = new ArrayList<Child>()
      10. }class Child{ public String name
      11. public int age
      12. }

      Positive Reactions
      1. It's working now.
      2. Thanks for the help guys...
      Negative Reactions
      1. I figured out a problem for some reason the rest-client that I was using was making the things worse.
      Other Reactions
      1. It was the issue with the input json.
      2. Not the application itself.

    29. Simplest method to Convert Json to Xml

      For a simple solution I recommend Jackson as it can transform arbitrarily complex JSON into XML with just a few simple lines of code. This demo uses Jackson-1.7.7 the newer 1.7.8 should also work) xml-databind/wiki Jackson-XML-Databind-0.5.3 not yet compatible with Jackson 1.8) and Stax2-3.1.1 . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jackson.map.ObjectMapper
      2. import com.fasterxml.jackson.xml.XmlMapper
      3. public class Foo{ public String name
      4. public Bar bar
      5. public static void main(String[] args) throws Exception { // JSON input: {"name":"FOO","bar":{"id":42}} String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}"
      6. ObjectMapper jsonMapper = new ObjectMapper()
      7. Foo foo = jsonMapper.readValue(jsonInput, Foo.class)
      8. XmlMapper xmlMapper = new XmlMapper()
      9. System.out.println(xmlMapper.writeValueAsString(foo))
      10. // <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo> }}class Bar{ public int id
      11. }

All usage scenarios for API com.fasterxml.jackson
  • How to (De)serialize field from object based on annotation using Jackson?

    Next is the actual ContextualSerializer which does the heavy lifting. This class looks at BaseResource properties and inspects them to see if the JsonId annotation is present. details

    Reactions - Positive 1, Negative 0, Others 0

    1. import com.fasterxml.jackson.core.*
    2. import com.fasterxml.jackson.databind.*
    3. import com.fasterxml.jackson.databind.ser.*
    4. import java.io.*
    5. public class ContextualJsonIdSerializer extends JsonSerializer<BaseResource>
    6. implements ContextualSerializer /*<BaseResource>*/ {
    7. private ObjectMapper mapper
    8. private boolean useJsonId
    9. public ContextualJsonIdSerializer(ObjectMapper mapper) {
    10. this(mapper, false)
    11. }
    12. public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
    13. this.mapper = mapper
    14. this.useJsonId = useJsonId
    15. }
    16. @Override
    17. public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider)
    18. throws IOException {
    19. if (useJsonId) {
    20. jgen.writeString(br.getId().toString())
    21. } else {
    22. mapper.writeValue(jgen, br)
    23. }
    24. }
    25. @Override
    26. public JsonSerializer<BaseResource> createContextual(
    27. SerializerProvider config, BeanProperty property)
    28. throws
    29. JsonMappingException { // First find annotation used for getter or field: System.out.println("Finding annotations for "+property)
    30. if (null == property) {
    31. return new ContextualJsonIdSerializer(mapper, false)
    32. }
    33. JsonId ann = property.getAnnotation(JsonId.class)
    34. if (ann
    35. == null) { // but if missing, default one from class ann = property.getContextAnnotation(JsonId.class)
    36. }
    37. if (ann == null) { //|| ann.length() == 0) { return this
    38. //new ContextualJsonIdSerializer(false)
    39. }
    40. return new ContextualJsonIdSerializer(mapper, true)
    41. }
    42. }

    Positive Reactions
    1. If so then could you please accept it?
    Other Reactions
    1. Did this answer the question?
    2. If not then what didn't it answer?

  • How to (De)serialize field from object based on annotation using Jackson?

    I used the JsonProperty annotation instead of wrapping the functionality in the ContextualSerializer because it seemed silly to reinvent the wheel. Finally the method that performs the serialization just creates an additional ObjectMapper and registers a module in the original ObjectMapper. details

    Reactions - Positive 1, Negative 0, Others 0

    1. import java.util.*
    2. import com.fasterxml.jackson.annotation.*
    3. public class Resource extends BaseResource{ private String name
    4. @JsonProperty("sub_resource_id") @JsonId private SubResource subResource
    5. @JsonProperty("sub_resource_ids") @JsonId private List<SubResource> subResources
    6. //getters and setters public String getName() {return name
    7. } public void setName(String name) {this.name = name
    8. } public SubResource getSubResource() {return subResource
    9. } public void setSubResource(SubResource subResource) {this.subResource = subResource
    10. } public List<SubResource> getSubResources() {return subResources
    11. } public void setSubResources(List<SubResource> subResources) {this.subResources = subResources
    12. }}

    Positive Reactions
    1. If so then could you please accept it?
    Other Reactions
    1. Did this answer the question?
    2. If not then what didn't it answer?

  • Removing a node in json in Java

    obsessiveCookie You're welcome and good luck!. This solution uses pure Jackson by setting the rootName on the ObjectReader . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import com.fasterxml.jackson.core.JsonProcessingException
    2. import com.fasterxml.jackson.databind.ObjectMapper
    3. import com.fasterxml.jackson.databind.ObjectReader
    4. import java.io.IOException
    5. public class User {
    6. public static void main(String[] args) throws JsonProcessingException, IOException {
    7. String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}"
    8. ObjectMapper mapper = new ObjectMapper()
    9. ObjectReader reader = mapper.reader(User.class).withRootName("User")
    10. User user = reader.readValue(json)
    11. System.out.println(user.getFirstname())
    12. }
    13. private String firstname
    14. private String lastname
    15. private String verified
    16. private String gender
    17. public String getFirstname() {
    18. return firstname
    19. }
    20. public void setFirstname(String firstname) {
    21. this.firstname = firstname
    22. }
    23. public String getLastname() {
    24. return lastname
    25. }
    26. public void setLastname(String lastname) {
    27. this.lastname = lastname
    28. }
    29. public String getVerified() {
    30. return verified
    31. }
    32. public void setVerified(String verified) {
    33. this.verified = verified
    34. }
    35. public String getGender() {
    36. return gender
    37. }
    38. public void setGender(String gender) {
    39. this.gender = gender
    40. }
    41. }

    Other Reactions
    1. +1 Was not aware of this alternative with jackson.

  • Pretty print JSON output in JBoss RESTful service

    I have a bit of a round about solution that prints it pretty decently. Not the best Pretty Print but it is enough You'll need the following from Maven Then you can change your method to something like this Since what it does is 1. details

    Reactions - Positive 0, Negative 0, Others 0

    1. import org.codehaus.jackson.JsonGenerationException
    2. import org.codehaus.jackson.map.JsonMappingException
    3. import org.codehaus.jackson.map.ObjectMapper
    4. import org.codehaus.jackson.map.ObjectWriter
    5. ...private final ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter()
    6. ...@GET@Path("books")@Produces({ MediaType.APPLICATION_JSON })public Response getBooks() { return Response.status(Status.OK).entity(WRITER.writeValueAsString(doGetBooks())).build()
    7. }

  • How to deserialize dynamic JSON fields with Jackson?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
    2. // import com.fasterxml.jackson.databind.ObjectMapper
    3. import org.codehaus.jackson.annotate.JsonTypeInfo
    4. import org.codehaus.jackson.map.ObjectMapper
    5. import javax.ws.rs.ext.ContextResolver
    6. import javax.ws.rs.ext.Provider
    7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
    8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
    9. this.defaultObjectMapper = new ObjectMapper()
    10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
    11. // .enableDefaultTyping()
    12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
    13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
    14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
    15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
    16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
    17. return this.defaultObjectMapper
    18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

  • How do I marshall nested key,value pairs into JSON with Camel and Jackson library?

    One way to represent this is What you'll end up with is this which although represents the data is far from ideal To get what you want use JsonAnyGetter. Something like this it could be made much easier to use) which produces I've been battling this today and your question inspired me to make it bloody work D The annotations are here annotations/wiki/Jackson-Annotations annotations/wiki/Jackson-Annotations See JUnit test here . details

    Reactions - Positive 7, Negative 1, Others 0

    1. public class Whatever {
    2. Map<String, String> keyvalues = new TreeMap<String, String>()
    3. @JsonProperty Map<String, String> visibility = new TreeMap<String, String>()
    4. @JsonAnyGetter
    5. public Map<String, String> getKeyvalues() {
    6. return keyvalues
    7. }
    8. }

    Positive Reactions
    1. I'm also using com.fasterxml.jackson.dataformat jackson-dataformat-csv 2.2.3 which seems to be importing it as well.
    2. well I hope it works for you.
    3. Thanks for the info.
    4. Please mark the answer as accepted :).
    5. Tom, thank you for the information.
    6. This test works for me.
    7. Thanks.
    Negative Reactions
    1. I discovered some Jackson library conflicts in my pom.xml that I'm cleaning up.
    Other Reactions
    1. I guess that's why its using an older version.
    2. Are you specifying that newer version in your pom.xml or your applicationContext.xml?
    3. What version Jackson are you using?
    4. I couldn't seem to get maven to pull down the fasterxml.jackson.library, so I downloaded the jackson-annotations-2.2.3.jar and added it to my classpath.
    5. Can you post your pom.xml and Camel applicationContext.xml files with your JUnit test?
    6. It now points my SensorGenerator class to the same library as yours, but I still don't get the nested visibility.
    7. Mine is imported as a dependency of restlet 2.2-M3.
    8. I added in the code you suggested, but when I run the program I only see the keyvalues in the JSON.
    9. URL_https://gist.github.com/TomDemeranville/7009250 .
    10. I looked in both and I don't seem to specify a version for the Jackson library.
    11. Btw, I looked under my .classpath under my Eclipse project and found out that yes, I am specifying multiple versions of the Jackson library, i.e.
    12. Part of my jackson is 2.1, other parts 2.2.3.
    13. I want to see if I can figure out what to add to call the newer Jackson library.
    14. here it is as a JUnit test.
    15. Here's all I've currently specified in my applicationContext.xml for marshalling to JSON: .
    16. I'm using camel-jackson 2.12.1.
    17. For some reason I don't see the nested visibility fields.
    18. I'll attach my SensorGenerator.java class, perhaps I'm missing something :-).
    19. You may have both versions on your classpath.
    20. I'm using Jackson 2.2.3 I think.
    21. Doh.
    22. The new version uses the fasterxml namespace.
    23. You are using an old version.
    24. And then further down in my .classpath I have: with a bunch of attributes set.
    25. You are using: import com.fasterxml.jackson.annotation.JsonAnyGetter;import com.fasterxml.jackson.annotation.JsonProperty; and I'm using import org.codehaus.jackson.annotate.JsonAnyGetter;import org.codehaus.jackson.annotate.JsonProperty; Did you specify the com.fasterxml library in your pom.xml?
    26. I have the following dependency in my pom.xml: org.apache.camel camel-jackson ${camel} where I define ${camel} above as 2.12.1.
    27. : .
    28. I just noticed that I'm using different libraries that you are for JsonAnyGetter and JsonProperty.

  • How do I parse JSON into a Map with lowercase keys using Jackson?

    Use a org.codehaus.jackson.map.KeyDeserializer put it in a SimpleModule and register that module with the Jackson ObjectMapper. UPDATE Actually this only will lowercase the top level map keys but not nested keys. details

    Reactions - Positive 0, Negative 0, Others 0

    1. import org.codehaus.jackson.map.KeyDeserializer
    2. import org.codehaus.jackson.map.ObjectMapper
    3. import org.codehaus.jackson.map.module.SimpleModule
    4. import org.codehaus.jackson.Version
    5. // ...class LowerCaseKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctx) throws IOException, JsonProcessingException { return key.toLowerCase()
    6. }}// ...ObjectMapper mapper = new ObjectMapper()
    7. SimpleModule module = new SimpleModule("LowerCaseKeyDeserializer", new Version(1,0,0,null))
    8. module.addKeyDeserializer(Object.class, new LowerCaseKeyDeserializer())
    9. mapper.registerModule(module)
    10. Map<String,Object> map = (Map<String,Object>) mapper.readValue(jsonStr, Map.class)

  • Jackson with JSON: Unrecognized field, not marked as ignorable

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @JsonIgnoreProperties(ignoreUnknown = true)

  • Jackson API: partially update a string

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. private static class KnownPart { @JsonProperty private Customer customer
    2. @JsonProperty private BrowserInfo browser
    3. } private static class Customer { @JsonProperty private int id
    4. @JsonProperty private String name
    5. @JsonProperty private Address[] addresses
    6. // just to make it more complex for this example public Customer(int id, String name, Address[] addresses) { this.id = id
    7. this.name = name
    8. this.addresses = addresses
    9. } public Customer() { } } private static class Address { @JsonProperty private String street
    10. @JsonProperty private String city
    11. public Address(String street, String city) { this.street = street
    12. this.city = city
    13. } public Address() { } } private static class BrowserInfo { @JsonProperty private String agent
    14. @JsonProperty private String version
    15. public BrowserInfo(String agent, String version) { this.agent = agent
    16. this.version = version
    17. } public BrowserInfo() { } }

  • Jackson API: partially update a string

    The code is pretty much the same than the original one with the difference that when an attribute from the KnownPart is written it's key is removed the tree which is in the UnknownPart object then it is easy to write the unknown part. The main object becomes The module only deals with UnknownPart objects private static class MyModule extends Module And the serializer is In the same time I wrote a benchmark to confirm or not that this solution is faster than JSONObject for big Json strings...The test compares read with JSONObject without mapping read with Jackson read with tree with Jackson read/write with JSONObject read/write with JacksonAnd it is indeed faster After 1000 iterations excluding potential class load or some initialization the JVM does i get in nano seconds . details

    Reactions - Positive 0, Negative 0, Others 0

    1. private static class UnknownPartSerializer extends BeanSerializerBase { public UnknownPartSerializer(BeanSerializerBase src) { super(src)
    2. } @Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { UnknownPart up = (UnknownPart) bean
    3. jgen.writeStartObject()
    4. serializeFields(up, jgen, provider)
    5. jgen.writeEndObject()
    6. } protected void serializeFields(UnknownPart bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { final BeanPropertyWriter[] props
    7. if (_filteredProps != null && provider.getSerializationView() != null) { props = _filteredProps
    8. } else { props = _props
    9. } int i = 0
    10. try { for (final int len = props.length
    11. i < len
    12. ++i) { BeanPropertyWriter prop = props[i]
    13. if (prop != null) { // can have nulls in filtered list prop.serializeAsField(bean, jgen, provider)
    14. bean.tree.remove(prop.getName())
    15. // new } } if (_anyGetterWriter != null) { _anyGetterWriter.getAndSerialize(bean, jgen, provider)
    16. } // new: Iterator<Entry<String, JsonNode>> it = bean.tree.getFields()
    17. while (it.hasNext()) { Entry<String, JsonNode> e = it.next()
    18. jgen.writeFieldName(e.getKey())
    19. jgen.writeObject(e.getValue())
    20. } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName()
    21. wrapAndThrow(provider, e, bean, name)
    22. } catch (StackOverflowError e) { /* 04-Sep-2009, tatu: Dealing with this is tricky, since we do not * have many stack frames to spare... just one or two
    23. can't * make many calls. */ JsonMappingException mapE = new JsonMappingException("Infinite recursion (StackOverflowError)", e)
    24. String name = (i == props.length) ? "[anySetter]" : props[i].getName()
    25. mapE.prependPath(new JsonMappingException.Reference(bean, name))
    26. throw mapE
    27. } } }

  • Jackson API: partially update a string

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Override public String getModuleName() { return "MyModule"
    2. } @Override public Version version() { return new Version(0, 0, 1, "SNAPSHOT")
    3. } @Override public void setupModule(Module.SetupContext context) { context.addBeanSerializerModifier(new org.codehaus.jackson.map.ser.BeanSerializerModifier() { private UnknownPartSerializer cs
    4. @Override public JsonSerializer modifySerializer(SerializationConfig config, BasicBeanDescription beanDesc, JsonSerializer<?> serializer) { return UnknownPart.class.isAssignableFrom(beanDesc.getBeanClass()) ? new UnknownPartSerializer((BeanSerializerBase) serializer) : serializer
    5. } })
    6. } }

  • Convert JSON from URL to JSONNode

    See methods etc etc. shameless plug And if you want to use JSON-Pointer to navigate your JSON coreutils you-can-also-do-that . details

    Reactions - Positive 5, Negative 1, Others 0

    1. final JsonPointer ptr = JsonPointer.of("current_observation", "display_location")
    2. final JsonNode displayLocation = ptr.get(node)

    Positive Reactions
    1. I will update them later, and hope that that solves the issue.
    2. OK, compiled successfully, many thanks.
    3. Update to the latest (2.2.x) ;).
    4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
    5. Please show the dependencies you have.
    Negative Reactions
    1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
    Other Reactions
    1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
    2. I changed it to:.
    3. There you are, as you can see some them are older than that.
    4. It does work; if it doesn't, it means you use an old version of jackson- databind.
    5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
    6. I've now altered the code.

  • Convert JSON from URL to JSONNode

    Thanks again. I see no reason why you'd need to use a Map<String Object when Jackson has the almighty JsonNode See the databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html javadoc for-JsonNode . details

    Reactions - Positive 5, Negative 1, Others 0

    1. final JsonNode node = new ObjectMapper().readTree(new URL("yourURLHere")

    Positive Reactions
    1. I will update them later, and hope that that solves the issue.
    2. OK, compiled successfully, many thanks.
    3. Update to the latest (2.2.x) ;).
    4. You should go with jackson-core, jackson-databind and jackson-annotations, all 2.2.x.
    5. Please show the dependencies you have.
    Negative Reactions
    1. I'm getting a NoSuchMethodException, and am struggling to know how to deal with it.
    Other Reactions
    1. com.springsource.com.fasterxml.jackson.core.jackson-core-2.0.2.jarjackson- annotations-2.0.2.jarjackson-core-asl-1.7.0.jarjackson-databind-2.2.1 .jarjackson-mapper-asl-1.0.0.jar.
    2. I changed it to:.
    3. There you are, as you can see some them are older than that.
    4. It does work; if it doesn't, it means you use an old version of jackson- databind.
    5. It wouldn't work with ObjectMapper, I get that this method can't be applied to a URL.
    6. I've now altered the code.

  • Jackson Library JSON Mapper to String

    Here is a complete working example that I have tested. If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. details

    Reactions - Positive 3, Negative 1, Others 0

    1. import java.io.IOException
    2. import java.util.List
    3. import org.codehaus.jackson.JsonGenerationException
    4. import org.codehaus.jackson.map.JsonMappingException
    5. import org.codehaus.jackson.map.ObjectMapper
    6. public class A {
    7. private List<B> b
    8. private int c
    9. public List<B> getB() {
    10. return b
    11. }
    12. public void setB(List<B> b) {
    13. this.b = b
    14. }
    15. public int getC() {
    16. return c
    17. }
    18. public void setC(int c) {
    19. this.c = c
    20. }
    21. public static void main(String[] args)
    22. throws JsonGenerationException, JsonMappingException, IOException {
    23. A a = new A()
    24. ObjectMapper mapper = new ObjectMapper()
    25. String temp = mapper.writeValueAsString(a)
    26. System.out.println(temp)
    27. }
    28. }
    29. class B {}

    Positive Reactions
    1. The method read works only if the List** b is empty..**
    2. I have change something in my Class A and the method save go.
    3. I have the functions save and read in 2 activities, the save go alway but the read function the firts time it go and the second time no.
    Negative Reactions
    1. Now i have another problem..
    Other Reactions
    1. I have substitute List** b new List**() with List** new ArrayList**().
    2. Are you using Eclipse?
    3. Meaning you do not have the appropriate jar file in your classpath.
    4. Why??
    5. The same function called in two activities..********
    6. See updated answer.
    7. If you copied my complete example and it did not run, then its a build path issue.
    8. Also, make sure you have get/set methods for each field in Class B.
    9. @user2520969 Did the example help?

  • Deserialize json with different object types

    Your class should be deserialized automatically if you modify it like this Note. Jackson 2.1 required**) Then to deserialize in your code . details

    Reactions - Positive 11, Negative 3, Others 0

    1. @JsonIgnoreProperties("team_id")@JsonNamingStrategy(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy)public class Registration implements Serializable { private static final long serialVersionUID = 1L
    2. private int id
    3. private String currentStatus
    4. private Date expirationTime
    5. @JsonIgnore private Volunteer volunteer
    6. @JsonIgnore private Team team
    7. public Registration() { } // other code}

    Positive Reactions
    1. Awesome it works!
    2. The result: succes is only meant to check if the user is signed in and if the input was correct (the response results from scanning a QR code).
    3. Well, no, it is not necessary.
    4. Jackson:1.9.12 I really appreciate your help :).
    5. Sounds strange to serialize Registration in SuccessfulOperation to me.
    6. and updated to Jackson 2.2.2 Thanks!
    7. Thanks for your quick answer!
    8. It is just the cleanest solution I know when dealing with "polymorphic JSON" ;) You still did not show what your Registration class looks like.
    9. The most recent version is 2.2.1!
    10. And good choice on Jackson... Android's JSON library is poor, to be honest.
    11. Hestitated to try GSon but Jackson is doing great :).
    Negative Reactions
    1. No problem!
    2. Argh, 1.9.12???
    3. I'm sorry, I added it as edit now.
    Other Reactions
    1. !.
    2. Is it really necessary to create those two subclasses?
    3. OK, hold on, I'll edit my answer with a fully annotated class; what Jackson version are you using?
    4. Upgrade :p My code will work with 2.1.x (edited), but I doubt it will with 1.9.12...
    5. I used jackson before in college when creating a java webapp.

  • Flatten JSON into Specific Format

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. class JsonConverter {
    2. private ObjectMapper objectMapper = new ObjectMapper()
    3. private JsonFactory jsonFactory = new JsonFactory()
    4. public String convert(File sourceJsonFile) throws Exception {
    5. SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile)
    6. List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity)
    7. return objectMapper.writeValueAsString(result)
    8. }
    9. private SourceEntity parseSourceEntity(File sourceJsonFile) throws Exception {
    10. JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile)
    11. return objectMapper.readValue(parser, SourceEntity.class)
    12. }
    13. private List<Map<String, String>> convertToTargetPropertiesMap(SourceEntity entity) {
    14. List<Map<String, String>> list = new ArrayList<Map<String, String>>()
    15. for (String[][] pairs : entity.getRecords()) {
    16. list.add(createPropertyMap(entity.getColumns(), pairs[0]))
    17. }
    18. return list
    19. }
    20. private Map<String, String> createPropertyMap(String[] names, String[] values) {
    21. Map<String, String> propertyMap = new LinkedHashMap<String, String>()
    22. for (int i = 0 i < values.length i++) {
    23. propertyMap.put(names[i], values[i])
    24. }
    25. return propertyMap
    26. }
    27. }

  • Flatten JSON into Specific Format

    After that we should write converter which can parse input JSON convert arrays into collection of maps and serialize it to target JSON. Finally we should write a little test Above program prints this JSON for your example input . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.io.File
    2. public class JacksonProgram {
    3. public static void main(String[] args) throws Exception {
    4. JsonConverter converter = new JsonConverter()
    5. String result = converter.convert(new File("/tmp/source.json"))
    6. System.out.println(result)
    7. }
    8. }

  • How to use JSONDeserializer to deserialize this string?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. public void readValueAsMap() throws Exception{ String value = "{\"226167\":\"myshow\",\"3193\":\"yourshow\"}"
    2. ObjectMapper mapper = new ObjectMapper()
    3. Map<String,String> valueAsMap = mapper.readValue(value, Map.class)
    4. Collection<String> values = valueAsMap.keySet()
    5. assertTrue(values.contains("226167"))
    6. assertTrue(values.contains("3193"))
    7. }

  • Mapping JSON data to Java objects

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.io.File
    2. import java.net.*
    3. import org.codehaus.jackson.map.ObjectMapper
    4. public class Movie {
    5. public static void main(String[] args) throws Exception {
    6. MovieResponse response
    7. ObjectMapper mapper = new ObjectMapper()
    8. response = mapper.readValue(new File("C:\\M.json"), MovieResponse.class)
    9. System.out.println(response)
    10. }
    11. }

  • Jackson deserializing nested polymorphic type

    Here is a code that works but I am not sure if it answers right to all the subtypes stuff. Remove the annotations from the other classes and it should work just tested it). details

    Reactions - Positive 0, Negative 0, Others 0

    1. @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
    2. public abstract static class FirstLevel {
    3. public abstract String getTestValue()
    4. }

  • How do I serialize an associated object differently using Jackson and annotations?

    The only thing it does is passing your annotation's value to your custom filter then it let the default serializer do the job. Finally . details

    Reactions - Positive 7, Negative 1, Others 0

    1. public class CustomSerializer extends JsonSerializer<Object> {
    2. private Class<?>[] _activeViews
    3. public CustomSerializer(Class<?>[] view) {
    4. _activeViews = view
    5. }
    6. @Override
    7. public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
    8. throws IOException, JsonProcessingException {
    9. BeanPropertyFilter filter = provider.getConfig().getFilterProvider().findFilter("CustomFilter")
    10. if (filter instanceof CustomFilter) {
    11. CustomFilter customFilter = (CustomFilter) filter
    12. // Tell the filter that we will filter our next property customFilter.setNextViews(_activeViews)
    13. provider.defaultSerializeValue(value, jgen)
    14. // Property has been filtered and written, do not filter anymore customFilter.setNextViews(null)
    15. } else { // You did not define a CustomFilter ? Well this serializer is useless... provider.defaultSerializeValue(value, jgen)
    16. }
    17. }
    18. }

    Positive Reactions
    1. I think it can give a thread safe and much simpler implementation.
    2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
    3. I'll end up doing something like your example, just with some tweaks.
    4. if it not a problem, please, do the refactoring with a multithreading.
    5. However, my solution is still useful if you have a lot of properties to filter.
    6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
    7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
    Negative Reactions
    1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
    Other Reactions
    1. I have some refactoring to do now...
    2. I ended up looking at BeanSerializerModifier.class.
    3. I will look at it tomorrow morning.
    4. I had already seen that but didn't have time and forgot.
    5. @RansomBriggs Hmm, I agree.

  • How do I serialize an associated object differently using Jackson and annotations?

    Here is some code working with Jackson 2.0 Define a custom annotation Define some Views Then you can write your entities like this. Note that you may define your own annotation instead of using JsonView Then here is where the code begins )First your custom filter Then a custom AnnotationIntrospector that will do two things 1. details

    Reactions - Positive 7, Negative 1, Others 0

    1. public static class CustomFilter extends SimpleBeanPropertyFilter {
    2. private Class<?>[] _nextViews
    3. public void setNextViews(Class<?>[] clazz) {
    4. _nextViews = clazz
    5. }
    6. @Override
    7. public void serializeAsField(
    8. Object bean, JsonGenerator jgen, SerializerProvider prov, BeanPropertyWriter writer)
    9. throws Exception {
    10. Class<?>[] propViews = writer.getViews()
    11. if (propViews != null && _nextViews != null) {
    12. for (Class<?> propView : propViews) {
    13. System.out.println(propView.getName())
    14. for (Class<?> currentView : _nextViews) {
    15. if (!propView.isAssignableFrom(
    16. currentView)) { // Do the filtering! return
    17. }
    18. }
    19. }
    20. } // The property is not filtered writer.serializeAsField(bean, jgen, prov)
    21. }
    22. }

    Positive Reactions
    1. I think it can give a thread safe and much simpler implementation.
    2. You don't have to, I'm happy with your answer cause it got me to the right place, just noting it if someone else lands here.
    3. I'll end up doing something like your example, just with some tweaks.
    4. if it not a problem, please, do the refactoring with a multithreading.
    5. However, my solution is still useful if you have a lot of properties to filter.
    6. Thank you for the bounty, and thank you for reporting that @JsonIgnoreProperties can be applied to properties (new since 2.0)!
    7. Awesome, I'm going to try and integrate your code this morning, and assuming it works I'll award the bounty.
    Negative Reactions
    1. One downside I see in your example is that the way you are using _nextViews appears to not be threadsafe.
    Other Reactions
    1. I have some refactoring to do now...
    2. I ended up looking at BeanSerializerModifier.class.
    3. I will look at it tomorrow morning.
    4. I had already seen that but didn't have time and forgot.
    5. @RansomBriggs Hmm, I agree.

  • Deserializing JSON flat object using immutable classes with Jackson

    So a simple approach would be to just provide no-argument private constructors for Jackson to use. If you really don't want to provide such extra constructors then it would be nice if a similar solution could be devised using @JsonCreator but I wasn't able to get such a thing to work. details

    Reactions - Positive 3, Negative 0, Others 0

    1. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
    2. import com.fasterxml.jackson.annotation.JsonUnwrapped
    3. import com.fasterxml.jackson.annotation.PropertyAccessor
    4. import com.fasterxml.jackson.databind.ObjectMapper
    5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"var1":"some_value", "var2":"some_other_value"} String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}"
    6. ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
    7. A a = new A(new Foo("some_value"), "some_other_value")
    8. System.out.println(mapper.writeValueAsString(a))
    9. // output: {"var1":"some_value","var2":"some_other_value"} A aCopy = mapper.readValue(jsonInput, A.class)
    10. System.out.println(mapper.writeValueAsString(aCopy))
    11. // output: {"var1":"some_value","var2":"some_other_value"} }}class Foo{ private final String var1
    12. Foo(String var1) {this.var1 = var1
    13. } private Foo() {this.var1 = null
    14. }}class A{ @JsonUnwrapped private final Foo foo
    15. private final String var2
    16. A(Foo foo, String var2) { this.foo = foo
    17. this.var2 = var2
    18. } private A() { this.foo = null
    19. this.var2 = null
    20. }}

    Positive Reactions
    1. Your solution is probably the only working in this situation.
    2. Using reflection would probably lead to possible memory visibility issues on that classes, and this is what I was trying to avoid using immutable classes.I think there is no other solution than querying an enhancement request to Jackson: thank you very much for your answer!.
    3. You are correct in that if a @JsonCreator is used to pass a property value, no setter will be used.
    Other Reactions
    1. However, I'm using final fields to force immutability hence thread safety without the need of using volatile fields, and I'm assuming that Jackson doesn't use reflection to set fields when providing a valid annotated constructor.

  • How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. A simple approach to serialize null keys as empty strings including complete examples of the two previously mentioned configurations) To suppress serializing Map entries with null keys further custom serialization processing would be necessary. details

    Reactions - Positive 0, Negative 0, Others 0

    1. import com.fasterxml.jackson.annotation.JsonInclude.Include
    2. import com.fasterxml.jackson.databind.SerializationFeature
    3. import java.util.HashMap
    4. import java.util.Map
    5. public class JacksonFoo {
    6. public static void main(String[] args) throws Exception {
    7. Map<String, Foo> foos = new HashMap<String, Foo>()
    8. foos.put("foo1", new Foo("foo1"))
    9. foos.put("foo2", new Foo(null))
    10. foos.put("foo3", null)
    11. foos.put(null, new Foo("foo4"))
    12. // System.out.println(new ObjectMapper().writeValueAsString(foos))
    13. // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) ObjectMapper mapper = new ObjectMapper()
    14. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
    15. mapper.setSerializationInclusion(Include.NON_NULL)
    16. mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer())
    17. System.out.println(mapper.writeValueAsString(foos))
    18. // output: // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}} }}class MyNullKeySerializer extends JsonSerializer<Object>{ @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName("")
    19. }
    20. }
    21. class Foo {
    22. public String bar
    23. Foo(String bar) {
    24. this.bar = bar
    25. }
    26. }

    Other Reactions
    1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  • How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    For example just remove the null key entries if possible before calling Jackson. That said To suppress serializing Map entries with null values you can still make use of WRITE_NULL_MAP_VALUES but note that it's moved to ackson/databind/SerializationFeature.html SerializationFeature To suppress serializing properties with null values you can l/jackson/annotation/JsonInclude.Include.html configure-the-ObjectMapper directly or make use of the annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonInclude.html @JsonInclude annotation or To handle null Map keys some custom serialization is necessary as best I understand. details

    Reactions - Positive 0, Negative 0, Others 0

    1. mapper.setSerializationInclusion(Include.NON_NULL)

    Other Reactions
    1. Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).

  • How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @JsonInclude(Include.NON_NULL)
    2. class Foo {
    3. public String bar
    4. Foo(String bar) {
    5. this.bar = bar
    6. }
    7. }

  • How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)

  • Deserialize JSON with Jackson without proper field

    The following examples demonstrate these points. Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. details

    Reactions - Positive 1, Negative 1, Others 0

    1. import java.util.HashMap
    2. import java.util.Map
    3. import com.fasterxml.jackson.annotation.JsonProperty
    4. import com.fasterxml.jackson.databind.ObjectMapper
    5. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
    6. ObjectMapper mapper = new ObjectMapper()
    7. Message message = mapper.readValue(inputJson, Message.class)
    8. System.out.println(mapper.writeValueAsString(message))
    9. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
    10. @JsonProperty("success") public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
    11. } @JsonProperty("success") public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
    12. }}

    Positive Reactions
    1. Thanks for your answers.
    Negative Reactions
    1. Obviously, I have something wrong in my code.
    Other Reactions
    1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
    2. But I can't make it work.
    3. I'll update the answer above to includes such an example.
    4. -- No.
    5. That what I thought...
    6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
    7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

  • Deserialize JSON with Jackson without proper field

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":true}"
    2. ObjectMapper mapper = new ObjectMapper()
    3. MessageWrapper wrappedMessage = mapper.readValue(inputJson, MessageWrapper.class)
    4. System.out.println(mapper.writeValueAsString(wrappedMessage))
    5. // output: {"success":true} }}class MessageWrapper{ @JsonUnwrapped @JsonProperty // exposes non-public field for Jackson use Message message
    6. }

  • Deserialize JSON with Jackson without proper field

    Example 1 with Message POJO exactly as defined in original question Example 2 with Message POJO modified to remove JsonProperty annotations. Example with MessageWrapper . details

    Reactions - Positive 1, Negative 1, Others 0

    1. import java.util.HashMap
    2. import java.util.Map
    3. import com.fasterxml.jackson.databind.ObjectMapper
    4. public class JacksonFoo{ public static void main(String[] args) throws Exception { // input: {"success":false} String inputJson = "{\"success\":false}"
    5. ObjectMapper mapper = new ObjectMapper()
    6. Message message = mapper.readValue(inputJson, Message.class)
    7. System.out.println(mapper.writeValueAsString(message))
    8. // output: {"success":false} }}class Message{ private Map<String, String> dataset = new HashMap<String, String>()
    9. public boolean isSuccess() { return Boolean.valueOf(dataset.get("success"))
    10. } public void setSuccess(boolean success) { dataset.put("success", String.valueOf(success))
    11. }}

    Positive Reactions
    1. Thanks for your answers.
    Negative Reactions
    1. Obviously, I have something wrong in my code.
    Other Reactions
    1. Well, in fact I forgot something important...I do not try to deserialize my JSON string into the object Message directly but in another class MessageWrapper which as a reference to an object messsage...I use the annotation @JsonUnwrapped on the field message of MessageWrapper to ask the deserialization of the object message.Am i forced to have my getter/setter in the root class MessageWrapper?
    2. But I can't make it work.
    3. I'll update the answer above to includes such an example.
    4. -- No.
    5. That what I thought...
    6. Just annotate the message field in MessageWrapper with @ JsonUnwrapped and with @ JsonProperty (or provide some other way for Jackson to know to use the field, e.g., making it public (don't actually do that)).
    7. @yann "Am i forced to have my getter/setter in the root class MessageWrapper?"

  • Reading multiple elements from json file

    If switching JSON-to/from-Java APIs is an option Jackson does have such a feature as demonstrated below. input.json JacksonFoo.java Output Update A similar solution using Gson. details

    Reactions - Positive 0, Negative 2, Others 0

    1. import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
    2. import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD
    3. import com.fasterxml.jackson.databind.ObjectMapper
    4. import java.io.File
    5. import java.util.Iterator
    6. public class JacksonFoo {
    7. public static void main(String[] args) throws Exception {
    8. ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY)
    9. Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"))
    10. while (thingsIterator.hasNext()) {
    11. System.out.println(thingsIterator.next())
    12. }
    13. }
    14. }
    15. class Thing {
    16. private String name
    17. @Override
    18. public String toString() {
    19. return String.format("Thing: name=%s", name)
    20. }
    21. }

    Negative Reactions
    1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
    2. This post is incorrect.
    Other Reactions
    1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
    2. Gson does have that (mis)feature.
    3. Updated answer accordingly.
    4. Ah, neat.
    5. I was thrown by the use of the word "Stream" in the GSON API.
    6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

  • Java + JSON and "errorjava.lang.RuntimeException: Stub!" error

    But code User user mapper.readValue("{\"name\": "first "Joe\" "last "Sixpack " User.class) System.out.println(user) returns me User@1394894How to get firstname and lastname. Jackson library resolved my problem thanks fge).This is working example it returns Joe . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.io.File
    2. import java.io.IOException
    3. import org.codehaus.jackson.JsonEncoding
    4. import org.codehaus.jackson.JsonFactory
    5. import org.codehaus.jackson.JsonGenerationException
    6. import org.codehaus.jackson.JsonGenerator
    7. import org.codehaus.jackson.JsonParseException
    8. import org.codehaus.jackson.map.JsonMappingException
    9. import org.codehaus.jackson.map.ObjectMapper
    10. class User { public enum Gender { MALE, FEMALE }
    11. public static class Name { private String _first, _last
    12. public String getFirst() { return _first
    13. } public String getLast() { return _last
    14. } public void setFirst(String s) { _first = s
    15. } public void setLast(String s) { _last = s
    16. } } private Gender _gender
    17. private Name _name
    18. private boolean _isVerified
    19. private byte[] _userImage
    20. public Name getName() { return _name
    21. } public boolean isVerified() { return _isVerified
    22. } public Gender getGender() { return _gender
    23. } public byte[] getUserImage() { return _userImage
    24. } public void setName(Name n) { _name = n
    25. } public void setVerified(boolean b) { _isVerified = b
    26. } public void setGender(Gender g) { _gender = g
    27. } public void setUserImage(byte[] b) { _userImage = b
    28. }}public class HelloWorld { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper()
    29. // can reuse, share globally try { User user = mapper.readValue("{\"name\":{ \"first\" : \"Joe\", \"last\" : \"Sixpack\" }}", User.class)
    30. System.out.println(user.getName().getFirst())
    31. } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace()
    32. } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace()
    33. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
    34. } }}

  • Jackson: deserialization of Map

    The JSON in the original question deserializes just fine for me using Jackson 1.9.2. . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.io.File
    2. import java.util.HashMap
    3. import java.util.Map
    4. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
    5. import org.codehaus.jackson.annotate.JsonMethod
    6. import org.codehaus.jackson.map.ObjectMapper
    7. import org.codehaus.jackson.type.TypeReference
    8. public class JacksonFoo{ public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
    9. Map<String, UUIDInfo> cache = mapper.readValue(new File("input.json"), new TypeReference<HashMap<String, UUIDInfo>>() {})
    10. System.out.println(cache)
    11. // output: // {0f861a9a-0a3e-40a7-8ff3-0b83d8070876=UUIDInfo: name=BAR.xml, filePath=/FOO/repo/BAR.xml, // f3cbb32e-b7b8-4af1-b48b-7ea393de7971=UUIDInfo: name=BLAH.xml, filePath=/FOO/repo/BLAH.xml, // 012009b6-26e9-4bc1-9050-2a4ac9546c7e=UUIDInfo: name=Check System.xml, filePath=/FOO/repo/Check System.xml} }}class UUIDInfo{ String name
    12. String filePath
    13. @Override public String toString() { return String.format("UUIDInfo: name=%s, filePath=%s", name, filePath)
    14. }}

  • Jackson deserialize object or array

    Following is an example of what such custom deserialization might look like. You could make use of DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY to force the input to always bind to a collection but that's probably not the approach I'd take given how the problem is currently described. details

    Reactions - Positive 4, Negative 2, Others 0

    1. import java.io.IOException
    2. import org.codehaus.jackson.JsonNode
    3. import org.codehaus.jackson.JsonParser
    4. import org.codehaus.jackson.JsonProcessingException
    5. import org.codehaus.jackson.Version
    6. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
    7. import org.codehaus.jackson.annotate.JsonMethod
    8. import org.codehaus.jackson.map.DeserializationContext
    9. import org.codehaus.jackson.map.JsonDeserializer
    10. import org.codehaus.jackson.map.ObjectMapper
    11. import org.codehaus.jackson.map.module.SimpleModule
    12. public class JacksonFoo{ public static void main(String[] args) throws Exception { // {"property1":{"property2":42}} String json1 = "{\"property1\":{\"property2\":42}}"
    13. // {"property1":[]} String json2 = "{\"property1\":[]}"
    14. SimpleModule module = new SimpleModule("", Version.unknownVersion())
    15. module.addDeserializer(Thing2.class, new ArrayAsNullDeserializer())
    16. ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY).withModule(module)
    17. Thing1 firstThing = mapper.readValue(json1, Thing1.class)
    18. System.out.println(firstThing)
    19. // output: // Thing1: property1=Thing2: property2=42 Thing1 secondThing = mapper.readValue(json2, Thing1.class)
    20. System.out.println(secondThing)
    21. // output: // Thing1: property1=null }}class Thing1{ Thing2 property1
    22. @Override public String toString() { return String.format(&qu