Editing JsonArray using Jackson library - java

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

Related

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 delete a JSON Array value in JSON Object

I have a JSON object as shown bellow.I would like to delete the value of the JSON array in the JSON Object using java.I tried using javascript and did it but I am confused with Java.
{
"aaa":"0px",
"bbb":"sadsda",
"ccc":
{
"ddd":
{
"eee":"initial","dsa":"none","asd":"none","caption":"","type":"image","title":"test.txt","align":"center","resolution":null,"captionMargin":"0px auto","href":"ttt/bbb.zzz?cfr=148c273959c9&od=1572cfa","componentbottombordersize":"none","height":null,"border":"0","padding":1,"das":"","src":"ooo","alt":"test.txt","componentbgcolor":"transparent","yandex":null,"target":"_self","hhhh":"none","size":"F","google":"none","microsoft":"100%","name":""
},
"freshdesk":
{
"oooo"
}
},
"width":600,
"zarket":
{
"array":["value1","value2"]
},
"type":"mailchimp",
"height":251
}
I want to delete value1 of array.How Can I do it using java?
Include this in maven
https://mvnrepository.com/artifact/com.google.code.gson/gson
Try this
Gson gson = new GsonBuilder().create();
YourJsonObject yourObj = gson.fromJson(reader, YourJsonObject.class);
if(yourObj.getZarket()!=null && yourObj.getZarket().getArray()!=null){
yourObj.getZarket().getArray().remove("value1");
}
// Assuming you will create a class YourJsonObject with the above attributes of json and the array attribute will be a list. if its an array, remove by searching the value in an array using iterations

Convert a string list/set to json objects in 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.

Parsing a really complicated nested json whose structure is always changing in JAVA

I have a really complicated nested json whose structure is always changing. I want to parse it in JAVA such that I can retrieve any element using the key/field name.
Option 1 - The easiest way to do this would be to convert/parse the json into a JAVA object.
I have tried everything (gson, JSONObject, Jackson...) But I cant convert the json unless I have a java class ready and since the json doesn't follow a fixed structure I cant convert it into a JAVA class. Is there any other library that can convert the json to a java object? (Without the need for a pre existing java class to convert the json into)
Option 2 - Or is there a way/library I can use, which if given a portion of the json, the program prints all the elements in the json file. Something like this...
StreetAddressLine
PrimaryTownName : value
CountryISOAlpha2Code :value
TerritoryAbbreviatedName :value
PostalCode : value
{"PrimaryAddress": [ {
"StreetAddressLine": [{"LineText": "492 Koller St"}],
"PrimaryTownName": "San Francisco",
"CountryISOAlpha2Code": "US",
"TerritoryAbbreviatedName": "CA",
"PostalCode": "94110",
"AddressUsageTenureDetail": [{"TenureTypeText": {
"#DNBCodeValue": 1129,
"$": "Rents"
}}],
"PremisesUsageDetail": [{"PremisesUsageFunctionDetail": [{"PremisesFunctionText": {
"#DNBCodeValue": 12058,
"$": "Manufacturing"
}}]}],
"CountyOfficialName": "San Francisco County",
"TerritoryOfficialName": "California",
"CountryGroupName": "North America",
"GeographicalPrecisionText": {
"#DNBCodeValue": 0,
"$": "Unknown"
},
"UndeliverableIndicator": false,
"MetropolitanStatisticalAreaUSCensusCode": ["San Francisco-Oakland-Hayward CA"],
"RegisteredAddressIndicator": false,
"ResidentialAddressIndicator": false
}]}
Thanks a lot!
Try using json-simple to parse the JSON into a bunch of nested JSONObject (which basically are maps) and JSONArray (which basically are lists) elements and extract the values yourself.
Just a node: PrimaryAddress indicates that there might be a SecondaryAddress as well, so the nesting should not change, otherwise it might be hard to determine things like which address StreetAddressLine belongs to.
In that case the better question would be: why does the structure change that often?
Ok I found a solution! I used the Jackson Parser
First map your jsonString to a JsonNode
JsonNode rootNode = mapper.readValue(jsonString, JsonNode.class);
Update the rootNode to contain the json for the required key:
rootNode = rootNode.findParent(key);
and then depending on if it is an array or a list handle it seperately:
if(rootNode.path(key).isArray()){
//key is the field in the json that you might be looking for
for (final JsonNode objNode : rootNode) {
for (Iterator<String> keyArray = objNode.getFieldNames(); keyArray.hasNext();){
fieldName = keyArray.next();
fieldValue = objNode.path(fieldName).asText();
if(fieldValue != ""){
System.out.println(fieldName + " = " + fieldValue);
}else{
arrayHandler(objNode,fieldName);
}
}
}
At each iteration check if the resulting JsonNode is an array or a list.
If it is a List handle it differently (Just iterate over the key value pairs like this)
for (Iterator<String> keyArray = rootNode.getFieldNames(); keyArray.hasNext();){
fieldName = keyArray.next();
fieldValue = rootNode.get(fieldName).asText();
System.out.println(fieldName + " = " + fieldValue);
}
After every iteration check what the next jsonNode is and call the respective handler recursively...

Parsing JSON server response into JSON Array

I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need

Categories

Resources