Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a property to a json string with jackson json

I am storing a json string into a text field in mysql. After the insertion, i want to update my json string and add the mysql line id into it with jackson json.

I have a java String which is in Json format

{
  "thing":"val"
}

I'm looking to add another K/V without writing lines of codes.

to finally have this :

{
  "thing":"val"
  "mysqlId":10
}

I can convert my String to a JsonNode :

ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree( jsonStr);

Looking to do something like this

json.put("mysqlId",10);
json.toString();

then update in my text field with new json string in mysql

I can't make it. I don't want use many class is there a simple way to do so with jackson?

like image 747
Dimitri Kopriwa Avatar asked May 15 '13 09:05

Dimitri Kopriwa


People also ask

What is JSON property annotation?

The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


1 Answers

Try casting your JsonNode to an com.fasterxml.jackson.databind.node.ObjectNode and then calling put set (or replace) on it.

like image 159
cmbaxter Avatar answered Oct 20 '22 01:10

cmbaxter