Jackson Object Mapper class given an error Spring mvc - json

Jackson Object Mapper class given an error Spring mvc
All required jar already added no error in project like jackson-core-asl, jackson-core-2.2.3 and jackson-all 1.9.0 still getting error

Remove the unnecessary jackson-all and jackson-core-asl dependencies.
Include the only one jackson-databind that automatically de/serializes the objects.
<jackson.version>2.8.9</jackson.version>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
Don't forget to return the whole List<Demo> instead of String.
#RequestMapping(value="/getJson", method = RequestMethod.GET)
public List<Demo> listJsonList {
// ...
return alldatalist;
}
And please, next time copy-paste the source code as a text, not as the image :)

Related

How to use default values of Kotlin (1.4.21) data class in Jackson (2.12.0) and Quarkus (1.11.1)

I am using Quarkus 1.11.1 with Kotlin 1.4.21 and Jackson 2.12.0.
I don't understand why when I send a POST request with a body of a data class that has a defined default parameter, this is not accepted and returns an error problem: Parameter specified as non-null is null
In the pom.xml file I have:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jackson</artifactId>
</dependency>
The Quarkus Documentation says (https://quarkus.io/guides/kotlin#kotlin-and-jackson):
If the com.fasterxml.jackson.module:jackson-module-kotlin dependency and the quarkus-jackson extension (or the quarkus-resteasy-extension) have been added to project, then Quarkus automatically registers the KotlinModule to the ObjectMapper bean (see this guide for more details).
I have a data class like:
data class MyAttributes
#BsonCreator constructor(
#BsonProperty("myId")
#JsonProperty("myId")
var myId: String,
#BsonProperty("name")
#JsonProperty("name")
val name: String,
#BsonProperty("data")
#JsonProperty("data", defaultValue = "{}")
var data: MutableMap<String, Any> = mutableMapOf()
)
I noticed that the defaultValue in the #JsonProperty annotation is not useful, because it is used only to document expected values (https://fasterxml.github.io/jackson-annotations/javadoc/2.12/com/fasterxml/jackson/annotation/JsonProperty.html#defaultValue--)
If I send a JSON like:
{
"myId": "AB123",
"name": "my attribute name"
}
I get the error described previously, and the default value of the data field is ignored.
If I send:
{
"myId": "AB123",
"name": "my attribute name",
"data": {}
}
I don't get an error, because I send also the data field.
Can you tell me where am I doing wrong, please?
Thanks
Do you have a default constructor? By default jackson requires a default constructor. This is not very common with data classes so you can either provide the constructor or you can do something like this:
#Bean
fun objectMapper(): ObjectMapper = ObjectMapper()
.registerKotlinModule()

Spring-boot 2 and swagger 2 (springfox) does not show model

I have created my patch endpoint (Json path specified in RFC 6902).
At UI generated by springfox my endpoint is shown, but the model example (only patch) did not show.
To use Json patch in my Spring-boot 2 project I have used that dependency on pom.xml.
<dependencies>
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-patch</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
At my endpoint, my code is:
#RestController
#RequestMapping(value = "/operation", produces = "application/json")
public class IntentController {
#RequestMapping(value = "/{id}",
method = RequestMethod.PATCH,
consumes = "application/json-patch+json")
public void updateValue(#PathVariable Long id, #RequestBody JsonPatch patch){ {
// ... do magic
}
#RequestMapping(value = "/{id}",
method = RequestMethod.GET)
public MyDto getValue(#PathVariable Long id){ {
MyDto dto = service.findById(id);
return dto;
}
#RequestMapping(method = RequestMethod.POST)
public void updateValue(#RequestBody MyDto dto){ {
service.insert(dto);
}
}
My GET and POST endpoints are generated fine with their example models in UI.
Only PATCH doesn't work fine... their example model didn't generate.
The problem lies with JsonPatch object, this object does not have any getter method, so Springfox library could not generate the model for request.
One possible solution may be like , you create a custom MyJsonPatch POJO with getter and setter and create a JsonPatch with the data of MyJsonPatch.
I can't found a solution to my problem, so I decided to use #ApiParam from Swagger to describe that this field is an RFC 6902 implementation.

how to convert txt file to jsonObject?

I'm getting txt file from resource folder(Spring).
and created the File
File file = new File(classLoader.getResource("files/example.txt").getFile());
And I want to convert this file to JsonObject file.
read the content of file using inputstream, then convert the stream to string.. use google gson json library to convert string to json:
http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html
You could also use Jackson for this. Jackson is one of the most complete JSON libraries around.
If you are using Maven, just include these dependencies:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
Then you can create an ObjectMapper instance with which you can create a JsonNode (similar to JsonObject) in this way:
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(in); // create a tree structure from the JSON
You can do whatever you want with this JsonNode:
jsonNode.fields().forEachRemaining(entry -> {
if(entry.getKey().endsWith(".ID")) {
entry.setValue(new TextNode(UUID.randomUUID().toString()));
}
});

SpringMvc controller to returns JSON, displays error: HTTP status 406

I am learning spring 4.2.4 by writing some webapp code.The idea is to return json file by controller.
I have already posted my questions before couple of days ago and still no i could get the right suggestions for my case. I am trying all the suggestions given by stackoverfolow none of the suggestions could work for me. Here is my controller:
.....
#RequestMapping(value="/getmessages",method=RequestMethod.GET, produces="application/json")
#ResponseBody
public Map<String,Object> getMessage(Principal prinicipal){
List<Message>message=null;
if(prinicipal==null){
message=new ArrayList<Message>();
}
else{
String username=prinicipal.getName();
message=usersService.getMessage(username);
}
Map<String,Object> data= new HashMap<String,Object>();
data.put("message", message);
data.put("number", message.size());
System.out.println("message has to be her\n"+message);
System.out.println("Number message has to be her is..."+message.size());
return data;
}
the message content which is to be retrieved from mysql is propely displayed in console.
The problem is conversion to JSON and return the result. I have been trying by change the jackson 1.9.x jar to jackson-fasterxml-2.x and it does not work. All other possible configuration of servlete also does not work for me.
When I add jackson-fasterxml-databind ....it displays file download dialogue box for filename"getmessages". to download and save...
I am very grateful for your help.
Finally I have solved this problem as follow:
I changed my return type from MAP to String and I converted my MAP to String in side my CONTROLLER as:
Converting my Map to String:
ObjectMapper mapper = new ObjectMapper();
String jsonFromMap = mapper.writeValueAsString(data);
I have also changed my dependencies as:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
Inside #RequestMapping change
produces=application/json
to
produces=text/html
I think the problem is with browser unable to understand application/json and returning Map............
Any how I did what I want to do even-though I do not know how I did it!

How to configure jackson in spring dispatcher servlet?

I want to send json data to controller in spring.How to configure jackson in dispatcher servlet and which jackson files to add in build path/lib?
You need to add the Jackson dependency first:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version> //your version//
</dependency>
You must add #ResponseBody statement in your code as well. For example:
public class JSONController {
#RequestMapping(value="{name}", method = RequestMethod.GET)
public #ResponseBody Shop getShopInJSON(#PathVariable String name) {
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
return shop;
}
}
Also, add < mvc:annotation-driven /> into your Spring XML configuration file.
You can find a full example of Jackson and Spring in this link.