Similar to GSON in Jackson for arrays - java

I am trying to convert an array or List (java) to JSON format. I have seen that in GSON we can do a the following:
data.add("hello");
data.add(someobject);
String gson = new Gson().toJson(data);
Is there any similar way in Jackson?

There is an equivalent in Jackson: ObjectMapper.writeValueAsString.
List data = new ArrayList();
ObjectMapper mapper = new ObjectMapper();
data.add("hello");
data.add(someobject);
String json = mapper.writeValueAsString(data);

Related

How to parse prettyprinted JSON with GSON

I'm connecting to some APIs. These calls return an already "prettyprinted" JSON instead of a one-line JSON.
Example:
[
{
"Field1.1": "Value1.1",
"Field1.2": "value1.2",
"Field1.3": "Value1.3"
},
{
"Field2.1": "Value2.1",
"Field2.2": "value2.2",
"Field2.3": "Value2.3"
}
]
When I try to parse a JSON like this with GSON it throws JsonSyntaxException.
Code example:
BufferedReader br = /*Extracting response from server*/
JsonElement jelement = new JsonParser().parse(br.readLine())
Is there a way to parse JSON files formatted like this?
EDIT:
I tried using Gson directly:
BufferedReader jsonBuf = ....
Gson gson = new Gson();
JsonObject jobj = gson.fromJson(jsonBuf, JsonObject.class)
But jobj is NULL when the code terminates.
I also tried to parse the string contained into the BufferedReader into a single line string and then using JsonParser on that:
import org.apache.commons.io.IOUtils
BufferedReader jsonBuf = ....
JsonElement jEl = new JsonParser().parse(IOUtils.toString(jsonBuf).replaceAll("\\s+", "");
But the JsonElement I get in the end is a NULL pointer...
I can't understand what I'm doing wrong...
BufferedReader::nextLine reads only one line. Either you read whole json from your reader to some String variable or you will use for example Gson::fromJson(Reader, Type) and pass reader directly to this method.
As your json looks like an array of json objects it can be deserialized to List<Map<String,String>> with usage of TypeToken :
BufferedReader bufferedReader = ...
Type type = new TypeToken<List<Map<String,String>>>(){}.getType();
Gson gson = new Gson();
List<Map<String,String>> newMap = gson.fromJson(bufferedReader, type);
You could also use some custom object instead of Map depending on your needs.

PrettyPrint JSON with Jackson

I am using jackson 2.8.4 and try to pretty-print (i.e. format nicely with indentation) some JSON that I have got in a one-line String called json.
I tried
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
and
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
json = mapper.writeValueAsString(json);
but the JSON String json still is just one line.
EDIT:
Before:
{"artifacts":[{"general":{"name":"jersey-client-2.26.jar","path":"doartifac/spielwiese-group-cache/org/glassfish/jersey/core/jersey-client/2.26/jersey-client-2.26.jar","pkg_type":"Maven","sha256":"3e44b7db8691eb0b2a6751eda888150b9ba1092a5805f11e4727fd4904407a41","component_id":"org.glassfish.jersey.core:jersey-client:2.26"},"issues":[],"licenses":[{"name":"CDDL-1.0","full_name":"Common Development and Distribution License (CDDL)\n 1.0","more_info_url":["http://www.opensource.org/licenses/cddl1.php","https://spdx.org/licenses/CDDL-1.0","https://spdx.org/licenses/CDDL-1.0.html","http://www.opensource.org/licenses/cddl1"],"components":["gav://org.glassfish.jersey.core:jersey-client:2.26"]},{"name":"GPL-2.0","full_name":"The GNU General Public License Version 2","more_info_url":["http://www.opensource.org/licenses/GPL-2.0","http://www.opensource.org/licenses/gpl-2.0.php","https://spdx.org/licenses/GPL-2.0","https://spdx.org/licenses/GPL-2.0.html","http://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html"],"components":["gav://org.glassfish.jersey.core:jersey-client:2.26"]}]}]}
After:
"{\"artifacts\":[{\"general\":{\"name\":\"jersey-client-2.26.jar\",\"path\":\"doartifac/spielwiese-group-cache/org/glassfish/jersey/core/jersey-client/2.26/jersey-client-2.26.jar\",\"pkg_type\":\"Maven\",\"sha256\":\"3e44b7db8691eb0b2a6751eda888150b9ba1092a5805f11e4727fd4904407a41\",\"component_id\":\"org.glassfish.jersey.core:jersey-client:2.26\"},\"issues\":[],\"licenses\":[{\"name\":\"CDDL-1.0\",\"full_name\":\"Common Development and Distribution License (CDDL)\\n 1.0\",\"more_info_url\":[\"http://www.opensource.org/licenses/cddl1.php\",\"https://spdx.org/licenses/CDDL-1.0\",\"https://spdx.org/licenses/CDDL-1.0.html\",\"http://www.opensource.org/licenses/cddl1\"],\"components\":[\"gav://org.glassfish.jersey.core:jersey-client:2.26\"]},{\"name\":\"GPL-2.0\",\"full_name\":\"The GNU General Public License Version 2\",\"more_info_url\":[\"http://www.opensource.org/licenses/GPL-2.0\",\"http://www.opensource.org/licenses/gpl-2.0.php\",\"https://spdx.org/licenses/GPL-2.0\",\"https://spdx.org/licenses/GPL-2.0.html\",\"http://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html\"],\"components\":[\"gav://org.glassfish.jersey.core:jersey-client:2.26\"]}]}]}"
try to check this one: Convert JSON String to Pretty Print JSON output using Jackson
You need first read existing JSON to Object, then serialize it.
Because now you are just serializing string.
UPD: You need to doo something like this:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = "here your ugly json";
Object jsonObject = mapper.readValue(json, Object.class);
String prettyFormatted = mapper.writeValueAsString(jsonObject);

JSONObject (org.json) to JsonElement(com.google.gson)

I am writing a java code in which i need to convert a JSONObject to JsonElement.Is there any way using which i can convert a JSONObject (org.json) to JsonElement(com.google.gson)?
One way that always works is to serialize the object to JSON and then parse it again:
JSONObject myData = ...
Gson gson = new Gson();
JsonElement element = gson.fromJson(myData.toString(), JsonElement.class);

Insert org.json.JSONArray into jackson ObjectNode

I have got stuck trying to insert a JSONArray into a Jackson ObjectNode. This is what I am trying to do:
public void myMethod(JSONArray jsonArray) {
ObjectNode payload = objectMapper.createObjectNode(0);
payload.put("array", /* jsonArray */);
payload.put(/* some other things */);
...
}
It feels like something really silly but what is actually the best way to do it?!
EDIT: I am sorry beacause I did not mention an important point, that is I have to serialize the ObjectNode once I finished building it, so using putPOJO() is not a possibility.
I like aribeiro's approach more. You can use the putPOJO() method to do this. For example:
// Incoming org.json.JSONArray.
JSONArray incomingArray = new JSONArray("[\"Value1\",\"Value2\"]");
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode payload = objectMapper.createObjectNode();
// Adds the JSONArray node to the payload as POJO (plain old Java object).
payload.putPOJO("array", incomingArray);
System.out.println(objectMapper.writeValueAsString(payload));
Javadoc can be found here.
Note: here's a previous implementation that I submitted using readTree():
// Incoming org.json.JSONArray.
JSONArray incomingArray = new JSONArray("[\"Value1\",\"Value2\"]");
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode payload = objectMapper.createObjectNode();
// Reads the JSON array into a Jackson JsonNode.
JsonNode jsonNode = objectMapper.readTree(incomingArray.toString());
// Sets the Jackson node on the payload.
payload.set("array", jsonNode);
System.out.println(objectMapper.writeValueAsString(payload));

How to convert ArrayList<object> to String and vice versa

I want to convert my ArrayList<object> to a JSON String and back to ArrayList<object>
But I really don't know how to do that :
Something like :
Convert
ArrayList<data> arrayData = new ArrayList<data>();
JSONObject retObject = new JSONObject();
retObject.put("data", new JSONArray(arrayData ));
Return convert
idk...
You can consider using a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Using Jackson:
ObjectMapper mapper = new ObjectMapper();
String listAsJson = mapper.writeValueAsString(oldList);
List<Object> newList= mapper.readValue(listAsJson ,new TypeReference<List<Object>>() {});
ArrayList<Product> arrayData = new ArrayList<Product>();
Gson gson = new Gson();
convert list to json object
String jsonCartList = gson.toJson(cartList);
convert json to your list
List<Product> prodList = gson.fromJson(jsonCartList, Product.class);

Categories

Resources