Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like JSON.stringify in Jackson?

Tags:

java

json

jackson

I find myself needing to JSON.stringify(objectMapper.writeValueAsString(someJavaBean)); server side in Java as I make an HttpClient call to another service in our infrastructure. Does Jackson have any such function? Is there an easy way to do this without adding another dependency to my project?

If it matters, we are Jackson 2.3.2.

What I need to do is convert some JSON like

{ "first_name" : "Robert", "last_name" : "Kuhar" }

Into a Javascript String like

"{ \"first_name\" : \"Robert\", \"last_name\" : \"Kuhar\" }"

Its not as simple as Replace all the quotes with \", is it? Like what happens if there are quotes embedded in the values? Or some of the values are single quote delimited? It seems like there should be a library call to do this.

Any advice?

like image 406
Bob Kuhar Avatar asked Feb 23 '15 20:02

Bob Kuhar


People also ask

How does Jackson build JSON?

We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data.

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.

Do you need JSON for Stringify?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

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.

What is the difference between JSON parse and JSON Stringify?

stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object. Save this answer.


1 Answers

String json = objectMapper.writeValueAsString(someObject);
String encodedASecondTime = objectMapper.writeValueAsString(json);

As simple as that. Not sure why you would want that, though, since a JSON value is a valid object literal already. You can do

String json = objectMapper.writeValueAsString(someObject);

and then generate javascript like

"var obj = " + json + ";"
like image 147
JB Nizet Avatar answered Oct 21 '22 02:10

JB Nizet