Convert a string list/set to json objects in java - java

I have a class named Order which contains one string list below
Set<String> items;
and when I convert this to JSON:
ObjectMapper mapperObj = new ObjectMapper();
String JSON = mapperObj.writeValueAsString(order);
System.out.println(JSON);
... I get output like below
"items":[
"xyz",
"aaa"
]
I'm looking for an output something like below
"items":[
{
"result":"xyz"
},
{
"result":"aaa"
}
]
I don't want to create a class separately for a single string.

You can use some API, like Jackson, for creating JSON object and print it into string. First create a json ArrayNode for your items. Then for each string in your items, create an ObjectNode like this,
ObjectNode node = mapper.createObjectNode();
node.put("result", "xyz");
and add them to the ArrayNode. Finally you print the JSON object out.

Related

What is the cleanest way to unwrap nested JSON values with Jackson in Java?

I have a JSON which looks like this (number of fields heavily reduced for the sake of example):
{
"content": {
"id": {"content": "1"},
"param1": {"content": "A"},
"param2": {"content": "55"}
}
}
Keep in mind, that I don't have control over it, I can't change it, that is what I get from API.
I've created a POJO class for this looking like that:
public class PojoClass {
private String id;
private String param1;
private String param2;
// getters and setters
}
Then I parse JSON with Jackson (I have to use it, please don't suggest GSON or else):
ObjectMapper om = new ObjectMapper();
JsonNode jsonNode = om.readTree(json).get("content");
PojoClass table = om.readValue(jsonNode.toString(), PojoClass.class);
And this doesn't work, because of id, param1 and param2 having JSON in them, not straight values. The code works fine with JSON like this:
{
"content": {
"id": "1",
"param1": "A",
"param2": "55"
}
}
But unfortunately the values I need are stored under "content" fields.
What is the cleanest way to resolve this?
I understand that I can hardcode this and extract all values into variables one by one in constructor or something, but there are a lot of them, not just 3 like in this example and obviously this is not the correct way to do it.
You can modify the JsonNode elements like "id": {"content": "1"} to {"id": "1"} inside your json string accessing them as ObjectNode elements with an iterator and after deserialize the new json obtained {"id":"1","param1":"A","param2":"55"} like below:
String content = "content";
ObjectMapper om = new ObjectMapper();
JsonNode root = om.readTree(json).get(content);
Iterator<String> it = root.fieldNames();
while (it.hasNext()) {
String fieldName = it.next();
((ObjectNode)root).set(fieldName, root.get(fieldName).get(content));
}
PojoClass table = om.readValue(root.toString(), PojoClass.class);
System.out.println(table); //it will print PojoClass{id=1, param1=A, param2=55}

Java - JSON Parsing to and Fro

I have been combing over multiple approaches with different JSON libraries, and cannot seem to find an elegant way to convert to and from with my JSON file in testing.
JSON file looks like this:
[
{
"LonelyParentKey": "Account",
"ProcessNames": [
{"Name": "ProcessOne",
"Sequence": "1"
},
{
"Name": "ProcessTwo",
"Sequence": "2"
},
{
"Name": "ProcessThree",
"Sequence": "3"
},
{
"Name": "ProcessFour",
"Sequence": "4"
}
]
}
]
In a QAF-based test using TestNG, am trying to import the values of the "ProcessName" key like this:
String lonelyParentKey = (String) data.get("LonelyParentKey");
ArrayList processNames = (ArrayList) data.get("ProcessNames");
I've seen that in the framework I'm using, I have multiple JSON library options, have been trying to use GSON after reading other SO posts.
So, next in the test code:
Gson gson = new Gson();
JSONArray jsa = new JSONArray(processNames);
What I am attempting to to create an object that contains 4 child objects in a data structure where I can access the Name and Sequence keys of each child.
In looking at my jsa object, it appears to have the structure I'm after, but how could I access the Sequence key of the first child object? In the REPL in IntelliJ IDEA, doing jsa.get(0) gives me "{"Name": "ProcessOne","Sequence": "1"}"
Seems like a situation where maps could be useful, but asking for help choosing the right data structure and suggestions on implementing.
TIA!
Not sure which library you're using, but they all offer pretty much the same methods. JSONArray looks like org.json.JSONArray, so that would be
JSONArray jsa = new JSONArray(processNames);
int sequenceFirstEntry = jsa.getJSONObject(0).getInt("Sequence");
Some JsonArray implementations also implement Iterable, then this also works
JSONArray jsa = new JSONArray(processNames);
for (JSONObject entry : jsa) {
int sequenceFirstEntry = entry.getInt("Sequence");
}
Any reason to not use DTO classes for your model?
e.g.
class Outer {
String lonelyParentKey;
List<Inner> processNames;
// getter/setter
}
and
class Inner {
String name;
String sequence;
// getter/setter
}
now your library should be able to deserialize your JSON string into a List. I have been using Jackson instead of GSON, but it should be similar in GSON:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
List<X> x = objectMapper.readValue(json, new TypeReference<List<X>>() {});

How to Parse JSON having data types with values?

I have an issue with JSON data.
In my Json it is having data types with values. not sure how to parse.
ex:
{
"id": "123456",
"name": {
"firstName": {
"String": "Nathon"
},
,
"lastName": {
"String": "Jason"
}
}.
Please help on this
public String map(ObjectNode jsonNode) throws Exception {
return value.get("id");
}
I tried with the above sample code , but i am able to parse only "id"
If you are using Jackson2 then get then name as JsonNode
JsonNode nameNode = value.path("name");
And then again get the firstName and lastName as JsonNode
JsonNode firstName = nameNode.path("firstName");
JsonNode lastName = nameNode.path("lastName");
From JsonNode firstName and JsonNode lirstName get the string value
String name1 = firstName.path("string").asText();
String name2 = lastName.path("string").asText();
Well first of all you don't have to mention the data types in order to parse a JSON appropriately, just create a POJO class matching the structure of JSON then use GSON to parse JSON into a java class
When your json is deserialized into ObjectNode then it is actually represented internally as a map key/value in which value can itself be again a map as is in your case. Visually if you look at it, it would be something like this.
So you would need to follow this structure using get(fieldName) to get the value OR an ObjectNode if it is nested . Remember if the return value is ObjectNode then simply printing it would just return the json fragment it represents, so you would need to call again 'get(fieldName)' on that object.

Editing JsonArray using Jackson library

My Json is like this
{
"A1":"1234",
"A2": "123",
"A3": "???",
"A4": "object, may not be populated.",
"A5": { },
"A6": { },
"A7":{
"B1": ["100"],
"B2": ["C"],
"B3": ["O", "A"]
},
"A8":{
"B4":["D1"],
"B5":["D2"],
"B6":["D3"],
"B7":["D4"],
"B8":["D5"],
"B9":["D6"],
"B10":["123"]
}
"ignoreThisField": "it is useless"
}
I am using Jackson library. I want to edit let's say element B4, which is inside A8 and it is of array type.
I tried below code
byte[] jsonData = readJson(JsonFilePath);
// Convert json String to object
POJOClass pojo= getValue(jsonData, POJO.class);
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true)
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, true);
JsonNode rootNode = objectMapper.readTree(jsonData);
// ((ObjectNode) rootNode).put("B4", "A" + "Somedata");
But it gives me output as
"B4":"[Somedata]"
instead of
"B4":["Somedata"]
which results in unexpected result.
B4 node contains list of data. How can we edit a node which is type array.
If we can not achieve this using jackson then is there any other library which can solve the problem?
I tried below links
Modify JsonNode of unknown JSON dynamically in Java and How to retrieve and update json array element without traversing entire json
but could not achieve much out of it
If i am not wrong you want to modify the B4 object present in the JSON data. To correctly do it you should use the below code.
JsonNode node = rootNode.get("A8");
List<String>list = new ArrayList<String>();//create a ArrayList
list.add("Anything"); //add data to arraylist
ArrayNode arrayNode = ((ObjectNode)node).putArray("B4"); //add the arraydata into the JSONData
for (String item : list) { //this loop will add the arrayelements one by one.
arrayNode.add(item);
}
you not using jackson lib fully.
<YOur pojo object> mypojo =objectMapper.readValue(jsonData, <yourpojo.class>);
now you can just use getter setter

How to convert map of JSON objects to JSON using GSON in Java?

I have a map of JSON objects as follows:
Map<String,Object> map = HashMap<String,Object>();
map.put("first_name", "prod");
JSONObject jsonObj = new JSONObject("some complex json string here");
map.put("data", jsonObj);
Gson gson = new Gson();
String result = gson.toJson(map);
Now if the "some complex JSON string here" was:
{"sender":{"id":"test test"},"recipients":{"id":"test1 test1"} }
and execute above code gives me something like:
{
"first_name": "prod",
"data": {
"map": {
"sender": {
"map": {
"id": "test test"
}
}
},
"recipients": {
"map": {
"id": "test1 test1"
}
}
}
}
}
I might have some syntax error up there, but basically I don't know why I am seeing objects wrapped around map's.
Update
according to comments, it is a bad idea to mix different json parsers.
i can understand that. but my case requires calling an external api which takes a hash map of objects that are deserialized using gson eventually.
is there any other object bedsides JSONObject that i can add to the map and still have gson create json out of it without extra 'map' structure? i do understand that i can create java beans and achieve this. but i'm looking for a simpler way since my data structure can be complex.
Update2
going one step back, i am given a xml string. and i have converted them to json object.
now i have to use an external api that takes a map which in turn gets converted to json string using gson in external service.
so i am given an xml data structure, but i need to pass a map to that function. the way i have described above produces extra 'map' structures when converted to json string using gson. i do not have control to change how the external service behaves (e.g. using gson to convert the map).
Mixing classes from two different JSON libraries will end in nothing but tears. And that's your issue; JSONObject is not part of Gson. In addition, trying to mix Java data structures with a library's parse tree representations is also a bad idea; conceptually an object in JSON is a map.
If you're going to use Gson, either use all Java objects and let Gson convert them, or use the classes from Gson:
JsonObject root = new JsonObject();
root.addProperty("first_name", "prod");
JsonElement element = new JsonParser().parse(complexJsonString);
root.addProperty("data", element);
String json = new Gson().toJson(root);
This has to do with the internal implementation of JSONObject. The class itself has an instance field of type java.util.Map with the name map.
When you parse the String
{"sender":{"id":"test test"},"recipients":{"id":"test1 test1"} }
with JSONObject, you actually have 1 root JSONObject, two nested JSONObjects, one with name sender and one with name recipients.
The hierarchy is basically like so
JSONObject.map ->
"sender" ->
JSONObject.map ->
"id" -> "test test",
"recipients" ->
JSONObject.map ->
"id" -> "test test1"
Gson serializes your objects by mapping each field value to the field name.
Listen to this man.
And this one.
I'd a similar problem and I finally resolved it using json-simple.
HashMap<String, Object> object = new HashMap<String,Object>;
// Add some values ...
// And finally convert it
String objectStr = JSONValue.toJSONString(object);
You may try out the standard implementation of the Java API for JSON processing which is part of J2EE.
JsonObject obj = Json
.createObjectBuilder()
.add("first_name", "prod")
.add("data", Json.createObjectBuilder()
.add("sender", Json.createObjectBuilder().add("id", "test test"))
.add("recipients", Json.createObjectBuilder().add("id", "test1 test1"))).build();
Map<String, Object> prop = new HashMap<String, Object>() {
{
put(JsonGenerator.PRETTY_PRINTING, true);
}
};
JsonWriter writer = Json.createWriterFactory(prop).createWriter(System.out);
writer.writeObject(obj);
writer.close();
The output should be:
{
"first_name":"prod",
"data":{
"sender":{
"id":"test test"
},
"recipients":{
"id":"test1 test1"
}
}
}

Categories

Resources