FAQ Database Discussion Community


How to covert JSON field name to a Java compatible property name while doing Jackson de-serialisation?

java,json,serialization,jackson,deserialization
I have ServerDetails pojo class. package org.vo; import org.codehaus.jackson.annotate.JsonProperty; public class ServerDetails { private Integer serverId; private String server_url; public ServerDetails() { } public ServerDetails(Integer serverId, String server_url) { this.serverId = serverId; this.server_url = server_url; } @JsonProperty("server-id") public Integer getServerId() { return serverId; } public void setServerId(Integer serverId) { this.serverId...

Unable to resolve any beans for Types [org.glassfish.jersey.message.filtering.spi.ObjectProvider]

java,json,jackson,jersey-2.0,wildfly-8
trying to move from Moxy to Jackson json media provider for my Jersey web service and found couple of issues which I can't resolve so far: first of all moxy was working fine for the same piece of code, but because we are using jackson everywhere in other projects I...

how to convert self iterating ArrlyList into json using Jackson [closed]

java,json,jackson
i want to convert List data into below json structure for this i had fetched data from mysql into arraylist and also written the pojo class EducationDTO . { "id": "1", "name": "EDUCATION", "data": "", "children": [ { "id": "1.1", "name": "STREAM-ENGG", "data": "", "children": [ { "id": "1.11", "name":...

Java FastXML JSON library: How to parse a nested JSON structure

java,json,jackson
The following here under is a Java program I am trying out to test JSON Processing using the org.fasterxml.jackson.core and the jackson-databind libraries in a streaming manner. The goal is to learn how to process JSON and capture the information I want. For now, what I want to accomplish is...

Jackson JSON mapping of Strings

spring-mvc,jackson
I used POJO's as @RequestBody parameters and they worked fine. But now I try something like this public void func(@RequestBody String s) and cant pass the value to String s. When I used POJO's I writes {"attribute" : "value"} in request and the question is what I should write in...

JSON: Python Output File to Java ObjectMapper - Wrong Sizes

java,python,json,jackson
So, I'm taking data from NLTK in Python and printing it to a file (with JSON) so I can load it into Java. This is what I'm doing in Python. wordcounts = nltk.ConditionalFreqDist((w.lower(), t) for w, t in brown.tagged_words()) print wordcounts.N() with open('test.json', 'w') as outfile: json.dump(wordcounts, outfile) Then, in...

Read the JSON file in the Jersey sources folder

java,json,jersey,jackson
I have Jersey project glassfish 2.18 and I am trying to read the JSON file routes.txt in this folder scr-main-sources with the Jackson 2.x . How can I get The InputStream of the text document file to get the data from it? I appreciate any help Code: FileReader fileReader =...

Handling multiple exceptions thrown by Jackson on Spring endpoint

java,spring,post,jackson,endpoints
In the code below I'm exposing a POST endpoint. The return value of the POST is determined by a Boolean attribute on the Success object : @RequestMapping(value="/new", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String createDispatch(@RequestParam(value="p1") String p1) { Success ds = new Success(); //Set a boolean on Success object...

Serialize HashMap to a JSON string while avoiding certain fields in Java

java,json,jackson
I have a map as below: Map map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); I need to convert this map into a JSON string. I know that this can be done using Jackson as below: new ObjectMapper().writeValueAsString(map); The problem is, I do not want to map...

How can I use Jackson to convert a javafx.scene.paint.Color to and from JSON

jackson,javafx-8
I am trying to find an example, but to no avail of how to reconstitute the javafx.scene.paint.Color JSON back into a POJO. When I create the JSON, the Color.RED is turned into this: { "annotationText" : "5/5/2015 12:18 PM", "pageNumber" : 0, "textColor" : { "red" : 1.0, "green" :...

jackson object property into primitive

java,json,rest,jackson
I have the follow json. { foo:{ id:1 }, name:'Albert', age: 32 } How can I deserialize to Java Pojo public class User { private int fooId; private String name; private int age; } ...

spring mvc (HATEOS) - jackson json serialize error

json,spring,spring-mvc,jackson,spring-hateoas
Its been 2 days I have been trying to resolve the json serialization issue in my project where I have bunch of entity classes mapped against each other with one-to-many relationships. So the error is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: com.softcons.cas.entities.CASWeightageMaster.casQuestionMaster, could...

Android JSON cant deserialize ArrayList out of START_OBJECT (JSON WITH BAD STRUCTURE)

java,android,json,jackson,gson
Hi guys i'am with a problem with some bad JSON structure from my client server, my client can't change and i have handle in this side. I'am creating POJO from JSON and I've already tried with GSON and now i'am using JACKSON because i thought the JACKSON TREE will help...

Android: deserialize dynamic JSON with Retrofit and Jackson

java,android,json,jackson,json-deserialization
I need to deserialize a dynamic JSON with unknown name of properties and I can't get it done. The JSON looks like this: { Player: [ { name: "name", surname: "surname", email: "email", photo: "photo", position: "position" } ], ... } So basically, this would be a JSON object containing...

How to instantiate class with nested abstract field with Jackson?

java,json,jackson,abstract
I've got following classes : public class City { Zoo zoo; } public class Zoo { Animal[] animals; } public abstract class Animal { String name; abstract void eat(); } I want to deserialize an instance of City class with Jackson. Howerer, since Animal is an abstract type, I've got...

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

java,json,compiler-errors,polymorphism,jackson
I am attempting to work through a tutorial from Programmer Bruce that is supposed to allow the deserialization of polymorphic JSON. The complete list can be found here Programmer Bruce tutorials (Great stuff btw) I have worked through the first five with no problems but I have hit a snag...

Jackson - Extract Data without Brackets, Commas, and =?

java,json,object,jackson,jackson-modules
I don't know a ton about Jackson, I'm just using it because I needed to share data from Python to Java. Anyway my code is pretty simple ObjectMapper mapper = new ObjectMapper(); Map<String,Object> data = mapper.readValue(new File(FileName), Map.class); System.out.println(data.get("SomeInput")); This is what I'm getting: {Y=0.830168776371308, Z=0.16877637130801687, X=0.0010548523206751054} I really just...

Java binary serializing fails because of jackson

java,json,serialization,jackson
I use jackson 2 to convert json into a java object. So far so good. But I also use hazelcast to distribute the objects in a cluster. Therefore all beans have to be java.io.Serializable. When I read the Object from json like so: ObjectMapper mapper = new ObjectMapper(); mapper.addMixInAnnotations(AbstractBean.class, MongoIdMixIn.class);...

Remove an array with Jackson

java,json,jackson
I'm trying to remove an array from a JSON file using Jackson. This is the structure of my JSON file: [ { "Lorem Ipsum ":3, "Lorem Ipsum ":14.2, "Lorem Ipsum ":5.8 }, { "thingToRemove":"stuff" } ] and this is what I've tried, without effect: for (JsonNode personNode : rootNode) {...

Java + jackson parsing error Unrecognized character escape

java,json,jackson,http-post,parse-error
I need to do a POST json string , using HttpClient. Following will be the code i have. From the other end the Json is mapped to an object. HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); String jsonData = "{ \"provider\" : null , \"password\" : \"a\", \"userid\"...

Avoiding writing DTO with unnecessary fields

json,jackson
I am making a call to third party REST Web Service. It returns me huge JSON string with lots of fields but I only need few of them. I am using jackson ObjectMapper like this : ObjectMapper mapper = new ObjectMapper(); myDetailDto = mapper.readValue(inputLine, new TypeReference<MyDetailDto>(){}); Is there a way...

Jackson: is it possible to replace the serializer set with @JsonSerialize annotation (e.g. with ObjectMapper)?

json,jackson,spring-security-oauth2
Quick question: is it possible to override @JsonSerialize annotation (using attribute) with ObjectMapper? I'm have spring-security-oauth2 integrated and I want to customize the way OAuth2Exception is serialized to JSON format. The problem is that this class uses @JsonSerialize(using = OAuth2ExceptionJackson2Serializer.class) I tried registering custom serializer with: SimpleModule module = new...

Why does Jackson 2 not recognize the first capital letter if the leading camel case word is only a single letter long?

java,json,spring,spring-mvc,jackson
I'm using Spring 4 MVC with Jackson 2 for my service. For one of the operations I have a request object that has an attribute where the leading camel case word this is only one letter in length: private String aLogId; This class has the appropriately named getters and setters:...

Jackson How to retrieve parent bean in a custom Serializer/Deserializer

java,json,serialization,jackson
In a custom serializer/deserializer, is there a way to retrieve the parent bean of the field ? For example : public class Foo { @JsonSerialize(using = MyCustomSerializer.class) public Bar bar; } public class Bar { } public class MyCustomSerializer extends JsonSerializer<Bar> { @Override public void serialize(Bar value, JsonGenerator jgen, SerializerProvider...

Could not read JSON

json,spring,spring-mvc,jackson
I have my controller like this following. RelationType is a field in Table class. I got the following exception. Any ideas? org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not construct instance of com.mycompany.myapp.core.domain.RelationType from String value 'unionetomany': value not one of declared Enum instance names: [unionetoone, unionetomany] at [Source: [email protected]; line:...

How to serialize output from custom method to JSON using Jackson?

java,json,jackson
I want to serialize output from specific method (The name of method doesn't start with get prefix). class MyClass { // private fields with getters & setters public String customMethod() { return "some specific output"; } } Example of JSON { "fields-from-getter-methods": "values", "customMethod": "customMethod" } Output from customMethod() is...

Deserialize jackson in spring boot

java,json,jackson,spring-boot
I am getting two types of json by calling RestTemplate {"results":[{"testing":{"name":"soham"}},{"testing":{"firstname":"john","lastname":"don"}}]} Now I am parsing data using JsonDeserializer public class CustomJacksonDeserialize extends JsonDeserializer<Activity> { @Override public Activity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, NullPointerException { ObjectMapper objectMapper = new ObjectMapper(); JsonNode actualObj =...

JSON nested property as not nested

java,json,rest,jackson
Is that possible in case where i have for instance class DefaultFruit { taste: String } class Fruit { fruit: DefaultFruit color: String } to provide some annotation @JSON annotation which convert the object structure to: { color: "", taste: "", } ...

Issue in parsing jackson

java,json,jackson,spring-boot
I am getting json using rest templete RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); test = restTemplate.getForObject(url,Test.class, params); I am getting json like {"object":"{\"id\":123,\"userId\":159,\"contentId\":1}"} Here is my POJO @JsonIgnoreProperties(ignoreUnknown = true) public class Test { @JsonProperty("id") private String id; public String getId() { return id; } public void setId(String id)...

Can Spring MVC deserialize JSON which can be object or array?

java,json,spring,spring-mvc,jackson
I have controller receiving JSON in request body, which can be object or array of objects. For example: { "id" : 1, "name" : "Nick", "surname" : "Cave" } and [ { "id" : 1, "name" : "Nick", "surname" : "Cave" }, { "id" : 2, "name" : "Jack", "surname"...

Jackson error: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/Versioned

java,json,jackson,ejb
I am working on Maven-EJB and want to convert a java object to JSON, I use Jackson jars lib but I got: java.lang.ClassNotFoundException: com.fasterxml.jackson.core.Versioned I added these dependencies in pom.xml file: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId>...

Is there a way to use Jackson's SerializationFeature with annotations

json,spring,jackson,resttemplate
I'm trying to use SerializationConfig.Feature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS but I'm not configuring the mapper myself, relying on annotations exclusively and letting Spring's RestTemplate (de)serialize automatically. Is there a way to enable the aforementioned feature in this scenario (i.e. annotations only)? NOTE: I'm using Jackson 1.x and can't upgrade due to other libs......

Working with multiple JSON objects in the same file with unknown key names using Jackson

java,json,jackson,fasterxml
Working on building the model for an application dealing with physical buildings. Ideally, we'd want something like this: City has multiple Offices, which have multiple Rooms, which have properties. We're using jackson to parse the JSON payload received from the API datasource, and it ends up looking a bit differently...

parse json file using gson/jackson java API

java,json,jackson,gson
I am a new bee to both JSON and GSON. My JSON structure is as mentioned below and i am using gson library to parse the json object and retrieve the values I am getting all null values from the getters. Can anyone help me on this. JSON file: {...

Does Jackson support java 8 stream()?

json,jackson,java-8,guava,java-stream
I would like to use Jackson's Tree Model with Java 8 stream API, like so: JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class); return jn.stream().anyMatch(myPredicate); However, JsonNode does not seem to implement stream() and I could not find any standard helpers to do so. JsonNode implements Iterable, so I can achieve the...

Get the data from the pojo classes of the JSON file

java,jackson
I have the following JSON array as file in my Jersey project in src/main/resources/routes.txt. I want to convert it to Java object to get the time in the case of mon-fri or sat or sun. I have generated the classes below with the help of this link. How can I...

Using builder to create nested XML

java,xml,jackson,builder,fasterxml
I'm using the Jackson set of classes to read in a CSV file, and convert it to xml, but need some advice on how to add a nested value. The code I'm using is: package reader; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema;...

How to ignore wrap element when parse json to dto

java,json,parsing,jackson
I have a json like this { "135": { "id": "135", "name": "My Awesome Washing Machine!", "powerswitch": { "available": "true", "state": "on", "reachable": "true", "locked": "false" }, "reference": { "id": "4", "name": "Lave-linge", "category_id":"2" } }, "491": { "id": "491", "name": "My Fridge", "powerswitch": { "available": "true", "state": "on", "reachable":...

cloud endpoint not respecting Jackson annotations

java,json,google-app-engine,jackson,google-cloud-endpoints
I have a class Organization with few date fields as follows. public class Organization { private String _id; private String name; @JsonDeserialize(using=JsonDateDeserializer.class) @JsonSerialize(using=JsonDateSerializer.class) private Date createdTime; // getters and setters } To handle the date in simple way on client side I convert date to long and send it to...

Jackson: final field written to after it is set by @JsonCreator?

java,json,security,jackson
It seems Jackson uses reflection to write additional attributes directly into fields even if a @JsonCreator constructor was used and the field is marked as final. Example: public class Test { static class X { final String s; @JsonCreator public X(@JsonProperty("a") String a) { s = "s"; } public String...

Jackson 1.x to 2.x and the meaning of backwards compatibility

json,jackson
By necessity, I need to upgrade from Jackson 1.x to 2.x. After reading the notes on the release, I thought it would be fine to upgrade, so long as I made the necessary code changes: http://wiki.fasterxml.com/JacksonRelease20 However, I realized after-the-fact that I still need to be able to deserialize data...

Export specific fields on XML extraction in Java

java,xml,spring,jackson
I am using @XmlRootElement annotation to get XML data from the database. Right now, if I put @XmlTransient to getters, the fields are ignored. For example: public class Student { private Integer studentId; private String studentName; @XmlTransient // Do not get student id public Integer getStudentId() { return this.studentId; }...

How to use Jackson to deserialise Array Like This?

java,android,json,jackson
How to deserialise simple? My JSON look like: { "ok": 1, "data": { "A": [ { "brand": "Aman", "logo": "http://zxmall.bluedoor.com.cn/uploads/logo/61.png" } ], "B": [ { "brand": "Base-DS", "logo": "http://zxmall.bluedoor.com.cn/uploads/logo/24.png" }, { "brand": "BB", "logo": "http://zxmall.bluedoor.com.cn/uploads/logo/46.png" }, { "brand": "Banane", "logo": "http://zxmall.bluedoor.com.cn/uploads/logo/11.png" } ], "C": [ { "brand": "cat", "logo": "http://zxmall.bluedoor.com.cn/uploads/logo/78.png"...

How do I fix this dependency issue in Clojure?

clojure,dependencies,jackson,leiningen
I'm having a lot of trouble fixing an issue where the dependencies for two different packages are colliding. My project.clj's dependencies look like this: :dependencies [[org.clojure/clojure "1.6.0"] [itsy "0.1.1"] [amazonica "0.3.22" :exclusions [commons-logging org.apache.httpcomponents/httpclient com.fasterxml.jackson.core/jackson-core]]]) My namespace looks like this: (ns crawler.core (:require [itsy.core :refer :all]) (:require [itsy.extract :refer :all])...

How to specify concrete type for abstract method param in Jersey/ Jackson?

java,jersey,jackson,jax-rs
I am using Jersey and have exposed a resource Resource which implements an Interface. One of the methods from Interface has a parameter a of type A which is an abstract class. Here is some code for explanation: //Interface.java public interface Interface { public void setA(A a); } //Resource.java @Path("/hello")...

How to register Jackson Jdk8 module in Restlet

json,jackson,java-8,restlet-2.0
Is it possible to register the jackson-datatype-jdk8 module in the Restlet org.restlet.ext.jackson extension package? I need to take advantage of the new Optional feature. My guess is that it should be accessible through the converter services (getConverterService()) but I can't find anything in the documentation that suggests exactly how setting...

415 Unsupported Media Type when I send json to spring controller

java,json,spring,jackson,type-conversion
I send POST http request with "Content-Type" "application/json" to my controller I have the following dependencies: <!--JSON--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> </dependency> the following controler method: @RequestMapping(value = "sendData.json", method = RequestMethod.POST,...

Hide JSON fields

java,hibernate,jackson
I have the hibernate entity, that pass to controller as parameter and I want to hide userID field. I use it for database operations and don`t need to show it as input parameter @Entity @Table(name = "user_sessions") public class UserSession{ @Column(name="uid") private Long userID; @Id @Column(name="access_key") private String accessKey; @Column(name="secret_key")...

Springboot REST application should accept and produce both XML and JSON

java,xml,rest,jackson,spring-boot
I am working on Springboot REST API. My application should consume and produce both XML and JSON. I came across the Jackson json Xml dependency. <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.5.4</version> </dependency> I added this in my pom.xml. Now I am able to accept xml input but the values are null when mapped...

Type mismatch: cannot convert from List to

java,jackson
I am trying to get the value of the arrivalTime from the JSON array stops but I am getting this error below Type mismatch: cannot convert from List to Map arrivalTime cannot be resolved or is not a field How can I fix it? I appreciate any help. Simple: [...

Get list of unknown fields from Jackson

java,json,jackson
I have a JSON schema, and a json string that matches the schema, except it might have a few extra fields. Jackson will throw an exception if those fields are there if I don't add objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);. Is there a way to obtain a collection of those extra fields to...

Json to yaml conversion does not work?

json,jackson,yaml
I am trying to convert json object to yaml file. But i am getting incorrect yaml file.some one help me to resolve this. Java code:- public class Trials { private JsonNodeFactory nodeFactory; public ArrayNode getJSONObject() { nodeFactory = JsonNodeFactory.instance; ArrayNode obj1 = nodeFactory.arrayNode(); ObjectNode obj11 = nodeFactory.objectNode(); ObjectNode obj12 =...

Jackson CSV missing columns

java,parsing,csv,jackson
I'm using Jackson CSV to parse a CSV file into POJOs. My issue is that if a row in the CSV has too few columns, the parser doesn't complain and just sets the rest of the fields to null. Parsing code: CsvMapper csvMapper = new CsvMapper(); csvMapper.addMixInAnnotations(Person.class, PersonCsvMixin.class); CsvSchema schema...

Convert a part of Json to HashMap using Jackson ObjectMapper

java,json,jackson,unmarshalling,object-object-mapping
I am trying to unmarshall a json file in a way such that few properties of Json are mapped into a HashMap that is present in my model class.Rest of the properties are mapped to the respective fields of the class.Please find the Json below: { "_id":2, "Name":"xyz", "Age":20, "MEMO_TEXT":"yyy",...

Using two JsonSerializers for single entity in Jackson

java,jackson,resteasy
I've found a way to implement my own serialization method extending the JsonSerializer<Foo>, overriding the serialize() method and registering the SimpleModule with everything. Here is what I have: @Provider @Produces(MediaType.APPLICATION_JSON) public class JacksonConfig implements ContextResolver<ObjectMapper> { @Override public ObjectMapper getContext(Class<?> aClass) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule fooModule...

Why is Jackson mapping these values twice, in differing case?

java,json,jackson
I'm mapping a Java object to JSON using Jackson, the object is a pretty simple pojo class that looks like this: import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; @JsonAutoDetect public class Area { @JsonProperty("Id") public int Id; @JsonProperty("Name") public String Name; public Area() { Name = ""; } public int getId() { return...

Best way for XML parsing in java [closed]

java,xml-parsing,jackson
I am using stax to parse an XML containg HTML and custom tags in java. The XML looks like this <html><div>Hello World</div><div><br /></div> <div><br /> <Resource type="audio/m4a" height="72.00" id="lh6rde3c1d39148804cea99b054f4cc4bb990" width="72.00" /> <br /><br /></div> <div><br /> </div><div>asfasdfasdfasdf</div><div><br /></div><div><br...

What is the GSON disableHtmlEscaping equivalent in JacksonJsonProvider

java,rest,jackson,gson,hateoas
I am trying to convert an URL e.g. https://api.test.com/cusomter?customer_id=1&customer_type=A but during serialization its getting converted into https://api.test.com/customer?customer_id\u003d1\u0026customer_type\u003dA I know that in GSON there is disableHtmlEscaping option to escape html safe conversion of = and & characters. Can you please let know the equivalaent option in JacksonJsonProvider....

Why can't I unwrap the root node and deserialize an array of objects?

java,json,jackson,deserialization,json-deserialization
Why am I not able to deserialize an array of objects by unwrapping the root node? import java.io.IOException; import java.util.Arrays; import java.util.List; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonRootName; import org.junit.Assert; import org.junit.Test; public class RootNodeTest extends Assert { @JsonRootName("customers") public static class Customer { public String email; } @Test public...

Jackson: how to read a String as List?

java,json,jackson
Our current class looks like public class Attributes { private String mapping; ..... and { "mapping": "displayName", ..... This has worked well and shipped to customers. The way we convert JSON to Attribute class is JSON.readValue(jsonFile, Attribute.class); Recently the requirement says, that mapping would be List<String> instead of String At...

Jackson deserialization circumventing final fields

java,json,jackson,immutability,lombok
Here's the code import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import lombok.ToString; public class Main { public static void main(String[] args) throws Exception { Fields f1 = new Fields(1); System.out.println(f1); ObjectMapper mapper = new ObjectMapper(); String str = mapper.writeValueAsString(f1); System.out.println(str); Fields f2 = mapper.readValue(str, Fields.class); System.out.println(f2); } @Data @ToString public static...

How to use Jackson Deserializer converter correctly

json,jackson
I wanted to try to use Jackson converter option to parse some custom strings. I have to deal with legacy string representations that have their own parser capable of taking a string and converting it into my desired class, IceComTerm. So I created a class that uses a field of...

Error while Parsing json into scala case class

java,scala,jackson,case-class
In my spring(mvc) web application, I am using org.codehaus.jackson.map.ObjectMapper in my scala code to map my json to scala objects using case classes. My Json String is an array of json objects objects. so I am using: val user = mapper.readValue(myJson, classOf[List[MyClass]]) This line throws an error: Exception in thread...

Jackson for validating xml against xsd

xml,jackson,xsd-validation
Does jackson have a validator for validating an xml against an xsd. I do not want to map the xml to a java class using jackson. If such kind of validation can be done using jackson, then how can I do it.

how to deserialize a blank json string value to null for java.lang.String

java,json,jackson
I am trying a simple json to de-serialize in to java object. I am however, getting empty String values for java.lang.String property values. In rest of the properties, blank values are converting to null values(which is what I want). my Json and Java class are listed below: Json string: {...

Catch json processing exception with dropwizard?

java,json,jackson,jersey-2.0,dropwizard
I have a dropwizard application with a global exception handler registered that implements ExceptionMapper<Throwable>. If I throw any runtime exception from within a resource the mapper gets hit. However, in a test I am posting JSON to to a resource with a missing type discriminator for a jackson polymorphic type....

DynamoDB JsonMarshaller cannot Deserialize List of Object

java,jackson,amazon-dynamodb
I have a Java class which is the data-model of a table in DynamoDB. I want to use the DynamoDBMapper to save and load items from Dynamo. One member of the class is a List<MyObject>. So I used the JsonMarshaller<List<MyObject>> to serialize and de-serialize this field. The list can be...

@RequestBody gives empty JsonObject when making a POST Request

java,json,spring,jackson
I have the following method: @RequestMapping(value = "/app/write", method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public @ResponseBody Status writeBuildData(@RequestBody JsonObject templateDataJSON){} Basically I make an Ajax POST request sending JSON, I always get an empty JsonObject {} as a result JsonObject templateDataJSON = "{}"; But if I use...

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.springframework.data.domain.Sort out of START_ARRAY token

java,json,jackson,spring-data
My objectMapper is fetching the value of type Page<User> as follows: userList = objectMapper.readValue(RestAdapter.get(url), new TypeReference<PageImplBean<User>>(){}); The PageImplBean extends PageImpl class as follows: public class PageImplBean<T> extends PageImpl<T> { private static final long serialVersionUID = 1L; private int number; private int size; private int totalPages; private int numberOfElements; private long...

What is the JacksonDB equivalent of db.collection.find({},{“fieldName”:1})?

java,mongodb,jackson,mongo-jackson-mapper
I am new to Jackson DB. Now I know that to get the entire document list of a collection using Jackson we need to do : COllectionClass.coll.find().toArray(); which is Jackson DB equivalent to the mongodb command : db.collection.find() So What is the Jackson DB equivalent of say : db.collection.find({},{"fieldName":1, "_id":0})...

Returning Map> as a JSON from Spring. Map key elements do not parse into JSON format

json,spring,dictionary,jackson
I have a question connected to returning Map<T, List<V>> as a JSON response. I have a spring server which returns JSON objects, but now I'm exploring problem with returning Map in this format. I want return a Map<T, List<V>> from my server as a JSON and display it in the...

Jersey: disable default JSON provider

java,jersey,jackson,jersey-2.0
i am using Jersey 2.17, JSON and automatic feature discovery. I have my custom JSON Provider extending JacksonJsonProvider. It's annotated with @Provider and automatically registerd, same as default one that comes with: <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> </dependency> I want to disable/exclude default one without giving up on feature scanning/manually registering everything....

How to convert input string to json string or json object using jackson in java [closed]

java,jackson
How to convert input string to json string or json object using jackson in java. Thanks in advance...

Spring MVC REST using @RequestBody List returns HTTP 400 syntactically incorrect

rest,spring-mvc,jackson
I am using Spring 4 + Jackson 2 and have written a fully functional POST method using @RequestBody on a custom class. This method has no trouble unmarshalling the object. @ResponseBody @RequestMapping(value="store", method = RequestMethod.POST) public ServiceResponse store(@RequestBody CustomClass list) { ... } // Request: { code: "A", amount: 200...

How to [de]serialize to pojo objects from JSON when there is mixed camel case in names

java,jackson,dropwizard
I'm using Dropwizard (which uses Jackson under the hood) to create a bridging API service. It connects to two other API's that are very similar (API1 and API2). I have my own POJO library that contains the request and response POJO's for API1 and API2. The only difference between those...

Jackson: add key identifier to the JsonArray

java,json,jackson
I am creating JsonArray with the aid of jackson and I am trying to add a key map_data to the craeted JsonArray to send it as response to the Android app. How can I add it to the JsonArray? I appreaciate any help. { "map_data": [ {"route": 2, "latitude": 89.667781,...

How to read JSON to a list of generic objects in java?

java,json,jackson,gson
I have to get data from a web service, I'm using Jackson but I have the same problem using Gson, I have no problem with single objects but when I receive several objects list it is not that easy for me. JSON received are like this: {"country": [ {"code":"AD","nombre":"Andorra","name":"Andorra"}, {"code":"AE","nombre":"Emiratos...

spring mvc restcontroller return json string

json,spring-mvc,jackson
I have a Spring MVC controller with the following method: @RequestMapping(value = "/stringtest", method = RequestMethod.GET) public String simpletest() throws Exception { return "test"; } This sits inside a controller that starts like this: @RestController @RequestMapping(value = "/root") public class RootController When I call other methods that return objects, those...

Set the Http status code if it is not set

java,jersey,jackson
I am trying to build a JSON string as server response with the aid of the Jackson library. If the route is not 0 I am getting tis response {"status":201,"routes":null} but I have problem to set the status variable to 204 in the SDBean class if the routeD is 0...

Marshall @Id to JSON while retaining Java 8 time formatting

java,json,spring,jackson,spring-boot
I'm trying to map an object to JSON. This works fine, but I also want to expose the @Id in JSON. I've found this answer on how to do that, but in order to use that solution, I have to extend RepositoryRestMvcConfiguration. When I extend this, my Java 8 time...

Jackson @JsonUnwrapped behaviour with custom JsonSerializer

java,json,jackson
I have two classes like this: public class A { String aProp = "aProp"; public String getAProp() { return aProp; } } public class B { String bProp = "bProp"; A a = new A(); @JsonProperty("bProp") public String getBProp() { return bProp; } @JsonSerialize(using = CustomSerializer.class) public A getA() {...

How to serialize/deserialize “splashed” complex type?

java,xml,jackson
I'm connecting to external XML API and I'm trying to parse it to POJOs using Jackson XmlMapper class. Part of the XML looks like this: <invoice> <some>element</some> <some_other>element</some_other> <currency>USD</currency> <cost>10.42</cost> <breakdown> <item id="1"> <description>blah blah</description> <cost>4.21</cost> </item> </breakdown> </invoice> And I want to parse the currency and cost elements in...

How to add message converter to restTemplate in xml configuration

rest,jackson,resttemplate,spring-json
I am using restTemplate for consuming json data from remote server, and then parsing the json in my java objects using jackson. I have added required message converters to my restTemplate by java code as: List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new MappingJacksonHttpMessageConverter());...

Parse Json with com.fasterxml.jackson instead of org.json

java,json,parsing,jackson
I was wondering if it is possible to do this exact operation but with the jackson library. String repo = response.toString(); JSONObject json = new JSONObject (repo); String nameOfUser = json.getJSONObject(facebookID).getString("name"); Thank you,...

Read json token (byte[]) as stream

java,json,jackson
Lets say that I have some json response like: { byteProp: [1, 3, 2, ... some very large byte content] } I would like to fetch byteProp as stream. I have started with JacksonStreamingApi and assumed that I should create parser like: JsonFactory jfactory = new JsonFactory(); JsonParser jParser =...

Java: Deserialize a json to object in rest template using “@class” in json -SpringBoot

java,jackson,spring-boot,deserialization,resttemplate
I have to instantiate a class which extends the abstract class from JSON using information in @class as shown below. "name": { "health": "xxx", "animal": { "_class": "com.example.Dog", "height" : "20" "color" : "white" } }, Here the abstract class is animal and dog extends the animal class. So using...

return just part of the bean with toJson()

java,json,jersey,jackson
I am trying to return {"status": its value}´in the case of routeD!=0 currently I am getting {"status":201,"routes":null} I would get the response in this form {"status":201} without "routes":null at the same time I dont want to lost the response of routeD==0 which is for example {"status":230,"routes":[1,9,3]} I appeciate any help....

Json response from retrofit+jackson convertor

android,jackson,retrofit
I want to know if it is possible to access the response body as a string when having success response. Here i get the success : serviceOne.editionsGet(Device, new Callback<Editions>() { @Override public void success(Editions editions, Response response) { //here i get my results } @Override public void failure(RetrofitError error) {...

@JsonInclude(JsonInclude.Include.NON_NULL does not work for double

java,json,jersey,jackson
I am trying to retieve {"status":201} in the case of route!=0 but I am getting {"status":201,"distance":0.0} how can I reach that with @JsonInclude or Jackson also without "distance":0.0? SDBean bean = new SDBean(); if (routeD != 0) { // Insert the data into the bus table bean.status = db.insertData(macD, routeD,...

Jackson: How to deserialize json with shorthand property value

java,json,jackson,deserialization
I am struggling to find out how to deserialize following JSON with shorthand conventions into Java POJOs using Jackson. [ { "id":1, "type": "simple" }, { "id":2, "type": { "kind": "simple" } }, { "id":3, "type": { "kind": "complex", "someOtherThing": "value" } } ] The "type" property here can be...

How to deserialize a JSON array to a singly linked list by using Jackson

jackson
I want to deserialize a JSON array to a singly linked list in Java. The definition of singly linked list is as the following: public class SinglyLinkedListNode<T> { public T value; public SinglyLinkedListNode next; public SinglyLinkedListNode(final T value) { this.value = value; } } How to deserialize a JSON string...

Null id property when deserialize json with jackson and Jackson2HalModule of Spring Hateoas

java,jackson,spring-data-rest,spring-hateoas,hal
My entity : public class User { private Integer id; private String mail; private boolean enabled; // getters and setters } File test.json (response from REST webservice) : { "_embedded" : { "users" : [ { "id" : 1, "mail" : "[email protected]", "enabled" : true, "_links" : { "self" :...

spring MVC use @JsonView on spring-data Page

spring-mvc,jackson,spring-data-jpa,jhipster
I'm using Spring-MVC, Spring-data-jpa, jackson on a Jhipster project. I managed to use the @JsonView annotation on an object and it works well when the method in the rest controller return a type ResponseEntity<List<MyObject>> but I can't make it work when the method return type is ResponseEntity<Page<MyObject>>. I've tried to...

Jackson Json UTF16

jackson
I'm new to Java and in C# this stuff is pretty straightforward but I'm struggling with it in Java. I'm entering some Chinese characters in a text box on the form but when Jackson Json serialises the object, it converts the Chinese chars into random bits of text. Does any...

Spring MVC RESTful web services with Jackson: How to restrict to subset of URLs

json,spring,rest,spring-mvc,jackson
Following the steps outlined here http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program , I've been able to setup my RESTful WS exactly how I want it. Now, I want to make this app context a hybrid of RESTful WS (under a specific URL prefix /myapp/rest/) and standard MVC mappings for the rest of the site. But...

Preventing infinite recursion in JAX-RS on JPA Entity Serialization (JSON) (without using Jackson annotations)

java,jpa,jackson,jax-rs,resteasy
I have an Entity as follows: @XmlRootElement @Entity @Table(name="CATEGORY") @Access(AccessType.FIELD) @Cacheable @NamedQueries({ @NamedQuery(name="category.countAllDeleted", query="SELECT COUNT(c) FROM Category c WHERE c.deletionTimestamp IS NOT NULL"), @NamedQuery(name="category.findAllNonDeleted", query="SELECT c from Category c WHERE c.deletionTimestamp IS NULL"), @NamedQuery(name="category.findByCategoryName", query="SELECT c FROM Category c JOIN c.descriptions cd WHERE LOWER(TRIM(cd.name)) LIKE ?1") }) public class Category...

How do I create a simple JSON Jersey 2.x RESTful web service on Glassfish 4?

json,rest,glassfish,jackson,jersey-2.0
I've spent days trying to figure this out. All I want to do is create a simple web service to return Lists of POJOs as JSON. Why is this so difficult? I'm starting with this in my POM: <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId>...

Create a JsonProcessingException

java,junit,jackson,mockito
I'm trying to create a JsonProcessingException to be thrown by a mock object. when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error")); However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?...

Design Java class for Jackson when JSON key has no one name but different values

java,json,parsing,jackson
How to model in Java (for Jackson library) following json file where the key is the file name so it has no (constant) name { "core/core-rwd/src/scss/_colors.scss": [ { "line": 1, "column": 13, }, I would like to have something like class MySet { ???? files; } class File { int...

Jackson Hibernate Spring returns JSON with foreign key not object

json,hibernate,spring-mvc,jackson
I have a problem when trying to get an object with multiple many to one relationships. I have a table Flight which has its Airport Destination/Origin and Airline. The Airport has its Country and the Airline has its Country. The problem is when the Country for the Airport and the...