Rectangle 27 4

The value field in your model is declared as Map while the corresponding JSON property can be either an empty array or a key-value map. Jackson cannot assign an empty array to a map field.

Assuming that you wish to solve the problem on the client side, you can modify the setValue method to accept a generic Object and then verify whether it is a map or an array (actually List since Jackson deserialize arrays as Java collections). Here is an example:

public class JacksonArrayAsMap {

    public static class Bean {
        private Map<String, Object> value;

        public void setValue(Object value) {
            if (value instanceof Map) {
                this.value = (Map<String, Object>) value;
            } else if (value instanceof List && ((List) value).size() == 0){
                this.value = Collections.EMPTY_MAP;
            } else {
                throw new IllegalArgumentException("Invalid value: " + value);
            }
        }

        @Override
        public String toString() {
            return "Bean{" +
                    "value=" + value +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        final String json1 = "{\"value\":{}}";
        final String json2 = "{\"value\":[]}";
        final String json3 = "{\"value\":{\"a\":\"b\"}}";
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(json1, Bean.class));
        System.out.println(mapper.readValue(json2, Bean.class));
        System.out.println(mapper.readValue(json3, Bean.class));
    }
}
Bean{value={}}
Bean{value={}}
Bean{value={a=b}}

Thanks for the answer, i'll try this out once i wear my hobby hat :)

Yay! confirm it works :) i'll continue on other available JSON feed from Graph API.

java - Jackson Can not deserialize empty array - Stack Overflow

java json serialization jackson
Rectangle 27 118

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

It works : I did the following: JavaType topMost = mapper.getTypeFactory().constructParametricType(MyWrapper.class, ActualClassRuntime.class); and then did the readValue and it finally worked :)

Yes, that does work -- thanks for pointing out the method for creating generic type other than Map/Collection type!

@StaxMan would it better to use ClassMate for these kind of things from now?

@husayt yes, technically java-classmate lib is superior. But integrating it with Jackson is bit tricky just because Jackson's own type abstraction is integrated part of API. For long term it'd be great to figure out proper way to make Jackson use classmate code, either embedded or via dep.

java - Jackson and generic type reference - Stack Overflow

java json generics jackson
Rectangle 27 57

Thanks, it works. Your solution perfectly makes sense, as Jackson mapper cannot initialize an inner class and return it.

Minor addition: Jackson can actually deserialize one kind of non-static inner classes -- those referenced directly by the parent class. But this is not the case here, as Test class is not being serialized. In this case non-staticness was probably accidental.

I would bet most of the "No suitable constructor" issues with nested POJOs are because of forgetting to mark it static. Thanks eugen!

java - Jackson ObjectMapper cannot deserialize POJO, throws an excepti...

java json spring jackson
Rectangle 27 57

Thanks, it works. Your solution perfectly makes sense, as Jackson mapper cannot initialize an inner class and return it.

Minor addition: Jackson can actually deserialize one kind of non-static inner classes -- those referenced directly by the parent class. But this is not the case here, as Test class is not being serialized. In this case non-staticness was probably accidental.

I would bet most of the "No suitable constructor" issues with nested POJOs are because of forgetting to mark it static. Thanks eugen!

java - Jackson ObjectMapper cannot deserialize POJO, throws an excepti...

java json spring jackson
Rectangle 27 57

Make it static. Jackson can not deserialize to inner classes share|improve this answer answered Oct 16 '12 at 16:47 eugen 4,81911822

Thanks, it works. Your solution perfectly makes sense, as Jackson mapper cannot initialize an inner class and return it.

Minor addition: Jackson can actually deserialize one kind of non-static inner classes -- those referenced directly by the parent class. But this is not the case here, as Test class is not being serialized. In this case non-staticness was probably accidental.

I would bet most of the "No suitable constructor" issues with nested POJOs are because of forgetting to mark it static. Thanks eugen!

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Jackson ObjectMapper cannot deserialize POJO, throws an excepti...

java json spring jackson
Rectangle 27 1

Firstly {["a", "b", 1]} is not a Valid Json Array (or JSON) .... JSON Array would look like this ["a", "b", 1]

Also you could deserialize the Json Array into a Java Object by writing a Custom Deserializer for the Java Object and Register it with Object Mapper using Module in Faster Xml.

Still I would suggest not using Array Representation for an Object.

Thanks. It's not me who is representing the object this way :-).

json - Java: FasterXML / jackson deserialize array without keys - Stac...

java json jackson fasterxml
Rectangle 27 28

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

List<product>
TypeReference
myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

A couple of other notes: your classes should always be CamelCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

jackson deserialization json to java-objects - Stack Overflow

java json object jackson deserialization
Rectangle 27 2

class CustomerDeserializer extends JsonDeserializer<Customer>
{
  public Customer deserialize(JsonParser p, DeserializationContext ctxt) 
                                        throws IOException, JsonProcessingException
  {
    JsonNode node = p.getCodec().readTree(p);
    String code = node.get("code").asText();
    String city = node.get("city").asText();
    String street = node.get("street").asText();
    Address adr = new Address(city, street);
    return new Customer(code, adr);
  }
}

json - Jackson Deserialization of Embedded Java Object - Stack Overflo...

java json jackson deserialization
Rectangle 27 262

To convert your object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

OMG thank you. I've been looking for the .writer() all morning. Now if I can just find the documentation page for it I will be all set.

Only thing is the String comes out escaped from the ObjectWriter. Use: new JSONObject(ow.writeValueAsString(msg)) if it's being sent out via Web Services like RESTful.

Out of interest why is it not os.writeValueAsJSONString(object)?

I'm facing this error, how to solve with your code No serializer found for class com.liveprocessor.LPClient.LPTransaction and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

libraries by the way : import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter;

Converting Java objects to JSON with Jackson - Stack Overflow

java json object jackson
Rectangle 27 260

To convert your object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

OMG thank you. I've been looking for the .writer() all morning. Now if I can just find the documentation page for it I will be all set.

Only thing is the String comes out escaped from the ObjectWriter. Use: new JSONObject(ow.writeValueAsString(msg)) if it's being sent out via Web Services like RESTful.

Out of interest why is it not os.writeValueAsJSONString(object)?

I'm facing this error, how to solve with your code No serializer found for class com.liveprocessor.LPClient.LPTransaction and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

libraries by the way : import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter;

Converting Java objects to JSON with Jackson - Stack Overflow

java json object jackson
Rectangle 27 1

public class JsonRequestResult {
    private String resource;
    private Object parameters;
    private ResultSetEntry[] resultSets;
}

public class ResultSetEntry {
    private String name;
    ...
}

Deserialize a Json Object with Jackson in Java - Stack Overflow

java json jackson deserialization
Rectangle 27 1

public class JsonRequestResult {
    private String resource;
    private Object parameters;
    private ResultSetEntry[] resultSets;
}

public class ResultSetEntry {
    private String name;
    ...
}

Deserialize a Json Object with Jackson in Java - Stack Overflow

java json jackson deserialization
Rectangle 27 10

I'm thinking of using something in the style of an Option class, where a Nothing object would tell me if there is such a value or not. Has anyone done something like this with Jackson (in Java, not Scala, et al)?

I'm using Guava's Optional for optional properties. If the field is missing from the JSON the property does not get assigned. I've solved this by initializing the fields using Optional.absent() but that means I can't use final fields which is a bit of a limitation.

java - Jackson: What happens if a property is missing? - Stack Overflo...

java jackson
Rectangle 27 147

As of Jackson 1.6, you can use:

JsonNode node = objectMapper.valueToTree(map);
JsonNode node = mapper.convertValue(object, JsonNode.class);

It appears that ObjectMapper.valueToTree wasn't added until Jackson 1.6, so the alternative is great for those of us that haven't upgraded yet!

Useful to know that the other way is also possible: there's a treeToValue method as well.

json - Convert Java Object to JsonNode in Jackson - Stack Overflow

java json jackson
Rectangle 27 2

Jackson is a High-performance JSON processor Java library. In this tutorial, we show you how to use Jacksons data binding to convert Java object to / from JSON.

For object/json conversion, you need to know following two methods :

//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
Note
Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.
1. Jackson Dependency
Jackson contains 6 separate jars for different purpose, check here. In this case, you only need jackson-mapper-asl to handle the conversion, just declares following dependency in your pom.xml

  <repositories>
    <repository>
        <id>codehaus</id>
        <url>http://repository.codehaus.org/org/codehaus</url>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
  </dependencies>
For non-maven user, just get the Jackson library here.



2. POJO
An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.

package com.mkyong.core;

import java.util.ArrayList;
import java.util.List;

public class User {

    private int age = 29;
    private String name = "mkyong";
    private List<String> messages = new ArrayList<String>() {
        {
            add("msg 1");
            add("msg 2");
            add("msg 3");
        }
    };

    //getter and setter methods

    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + ", " +
                "messages=" + messages + "]";
    }
}


3. Java Object to JSON
Convert an user object into JSON formatted string, and save it into a file user.json.

package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) {

    User user = new User();
    ObjectMapper mapper = new ObjectMapper();

    try {

        // convert user object to json string, and save to a file
        mapper.writeValue(new File("c:\\user.json"), user);

        // display to console
        System.out.println(mapper.writeValueAsString(user));

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

  }

}
Output

{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
Note
Above JSON output is hard to read. You can enhance it by enable the pretty print feature.
4. JSON to Java Object
Read JSON string from file user.json, and convert it back to Java object.

package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) {

    ObjectMapper mapper = new ObjectMapper();

    try {

        // read from file, convert it to user class
        User user = mapper.readValue(new File("c:\\user.json"), User.class);

        // display to console
        System.out.println(user);

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

  }

}
User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]

How to convert input string to json string or json object using jackso...

java jackson
Rectangle 27 3

You can use a custom deserializer for this feld. Here is one that returns the string if it's there, or null in any other case:

public class Hello {

    @JsonDeserialize(using = StupidValueDeserializer.class)
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

public class StupidValueDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonToken jsonToken = p.getCurrentToken();
        if (jsonToken == JsonToken.VALUE_STRING) {
            return p.getValueAsString();
        }
        return null;
    }
}

java - Use Jackson to deserialize JSON string or object into a String ...

java json jackson
Rectangle 27 1

Hi found two solutions using jackson fasterxml api.

In the first one you can just use the findValue method on the jsonNode and pass in the string value of property/object you are looking for

String jsonresponse = "above json string";
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(jsonresponse);
    jp.setCodec(new ObjectMapper());
    JsonNode jsonNode = jp.readValueAsTree();
    JsonNode reportNode = jsonNode.findValue("report");     
    ObjectMapper mapper = new ObjectMapper();
    Report report = mapper.convertValue(reportNode, Report.class);

This other solution use JsonToken which travels the json response till you find what you are looking for

JsonFactory factory = new JsonFactory();       
    factory.setCodec(new ObjectMapper());
    JsonParser  parser  = factory.createParser(jsonresponse);
    while(!parser.isClosed()){
        JsonToken jsonToken = parser.nextToken();

        if(JsonToken.FIELD_NAME.equals(jsonToken)){
            String fieldName = parser.getCurrentName();
            if("report".equals(fieldName)) {
                jsonToken = parser.nextToken();
                Report report = parser.readValueAs(Report.class);       
            } else {
                jsonToken = parser.nextToken();
            }
        }
    }

very good. You tought me new features where I thought I knew it all :)

Jackson JSON Java nested object and arrays - Stack Overflow

java json jackson objectmapper
Rectangle 27 1

The solution for this is jayway Java implementation for JsonPath.JsonPath is the json equivalent for the XPath query language for XML. the query langauge is quite powerful, as can be seen in the examples on the github readme.

Here is a quick demo to get you started:

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import com.jayway.jsonpath.*;
import net.minidev.json.JSONArray;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;

public class JsonPathDemo2
{
    public static void main(String[] args)
    {
        // query: search for any report property below root 
        String jsonPathQuery = "$..report";

        try (InputStream is = Files.newInputStream(Paths.get("C://temp/xx.json"))) {
            Object parsedContent = 
                    Configuration.defaultConfiguration().jsonProvider().parse(is, StandardCharsets.UTF_8.name());
            System.out.println("hasJsonPath? " + hasJsonPath(jsonPathQuery).matches(parsedContent));
            Object obj = JsonPath.read(parsedContent, jsonPathQuery);
            System.out.println("parsed object is of type " + obj.getClass());
            System.out.println("parsed object to-string " + obj);
            JSONArray arr = (JSONArray)obj;
            System.out.println("first array item is of type " + arr.get(0).getClass());
            System.out.println("first array item to-string " + arr.get(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
hasJsonPath? true
parsed object is of type class net.minidev.json.JSONArray
parsed object to-string [{"reportId":"reportid1","reportDetails":[{"code":"1","rating":"good"},{"code":"2","rating":"bad"},{"code":"3","rating":"fair"}]}]
first array item is of type class java.util.LinkedHashMap
first array item to-string {reportId=reportid1, reportDetails=[{"code":"1","rating":"good"},{"code":"2","rating":"bad"},{"code":"3","rating":"fair"}]}

Hi thanks for your response. I was looking for something in the jackson api. I found the answer to it. I will put the solution here. Thanks though.

Jackson JSON Java nested object and arrays - Stack Overflow

java json jackson objectmapper
Rectangle 27 6

public static <T> List<T> parseJsonArray(String json,
                                         Class<T> classOnWhichArrayIsDefined) 
                                         throws IOException, ClassNotFoundException {
   ObjectMapper mapper = new ObjectMapper();
   Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
   T[] objects = mapper.readValue(json, arrayClass);
   return Arrays.asList(objects);
}

java - How to use Jackson to deserialise an array of objects - Stack O...

java json jackson
Rectangle 27 1

You need to write your own Jackson JsonSerializer to create custom JSON string from Java object as per the need.

Here are the nice posts along with example

The same thing you can achieve using GSON JsonSerializer

GSON Serialiser
List<MyClass> list = new ArrayList<MyClass>();

MyClass myClass1 = new MyClass();
myClass1.setId("book-id1");
myClass1.getOptionalData().put("type", "book");
myClass1.getOptionalData().put("year", "2014");
list.add(myClass1);

MyClass myClass2 = new MyClass();
myClass2.setId("book-id2");
myClass2.getOptionalData().put("type", "book");
myClass2.getOptionalData().put("year", "2013");
list.add(myClass2);

class MyClassSerialiser implements JsonSerializer<MyClass> {

    @Override
    public JsonElement serialize(final MyClass obj, final Type typeOfSrc,
            final JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("id", obj.getId());
        Map<String, String> optioanlData = obj.getOptionalData();
        if (optioanlData.size() > 0) {
            for (Map.Entry<String, String> entry : optioanlData.entrySet()) {
                jsonObject.addProperty(entry.getKey(), entry.getValue());
            }
        }

        return jsonObject;
    }
}

String jsonString = new GsonBuilder().setPrettyPrinting().
        .registerTypeAdapter(MyClass.class, new MyClassSerialiser()).create()
        .toJson(list);

System.out.println(jsonString);
[
    {
        "id": "book-id1",
        "type": "book",
        "year": "2014"
    },
    {
        "id": "book-id2",
        "type": "book",
        "year": "2013"
    }
]

json - jackson serialization for Java object with Map? - Stack Overflo...

java json jackson