Delete a child attribute from json file - java

I have the following HTTP JSON-response in Java, which represents a user object.
{
"account": "Kpatrick",
"firstname": "Patrick",
[
],
"instances":
[
{
"id": "packerer-pool",
"key": "packerer-pool123",
"userAccount": "kpatrick",
"firstname": "Patrick",
"lastname": "Schmidt",
}
],
"projects":
[
{
"id": "packerer-projectPool",
"projectKey": "projectPool-Pool",
"cqprojectName": "xxxxx",
},
{
"id": "packerer-secondproject",
"projectKey": "projectPool-Pool2",
"cqprojectName": "xxxx",
},
{
"id": "packerer-thirdproject",
"projectKey": "projectPool-Pool3",
"cqprojectName": "xxxx",
}
],
"clients":
[
],
"dbid": 76864576,
"version": 1,
"id": "dbpack21"
}
Now, I want to search a specific project with the help of the projectkey (for example "projectPool-Pool2"). After that, I want to delete the element completely. Because my target is to send a HTTP post-call without this project.
The result should be similar to below for my HTTP post-call:
{
"account": "Kpatrick",
"firstname": "Patrick",
[
],
"instances":
[
{
"id": "packerer-pool",
"key": "packerer-pool123",
"userAccount": "kpatrick",
"firstname": "Patrick",
"lastname": "Schmidt",
}
],
"projects":
[
{
"id": "packerer-projectPool",
"projectKey": "projectPool-Pool",
"cqprojectName": "xxxxx",
},
{
"id": "packerer-thirdproject",
"projectKey": "projectPool-Pool3",
"cqprojectName": "xxxx",
}
],
"clients":
[
],
"dbid": 76864576,
"version": 1,
"id": "dbpack21"
}
First i have parsed the response to a string.
private static String getContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity == null) return null;
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = reader.readLine();
reader.close();
return line;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
And now i am trying to search the specific project, but i don't know how to continue.
String StringResponse = getContent(JsonResponse);
JSONObject jsonObject = new JSONObject(StringResponse);
JSONArray ProjectsArray= jsonObject.getJSONArray("projects");
Is that approach correct?
Best Regards!

Once you have your array, try something like...
// Array to store the indexes of the JSONArray to remove
ArrayList<Integer> indexesToRemove = new ArrayList<Integer>();
// Iterate through projects array, check the object at each position
// if it contains the string you want, add its index to the removal list
for (int i = 0; i < projectsArray.length; i++) {
JSONObject current = projectsArray.get(i);
if (current.get("projectKey") == "**DESIRED PROJECT KEY**") {
indexesToRemove.add(i);
}
}
Now you can iterate through your indexes to remove, and remove the corresponding object from the array with the JSONArrays remove method (not sure what it is called, the code above is from memory). Make sure to remove your items BACKWARDS, otherwise you will delete earlier items, which will change the indexes, resulting in your removing an incorrect item if you then remove another index.
// Going through the list backwards so we can remove the highest item each
//time without affecting the lower items
for (int i = indexesToRemove.size()-1; i>=0; i--) {
projectsArray.remove(indexesToRemove.get(i));
}

Related

How would I access this key within a JSON object in Java?

I've been having some problems iterating through a JSON object in Java.
Specifically, I'd like to save each value for "name" to the string array "nameList". I've looked up how to do this, and I haven't found a way for this situation.
String[] nameList = new String[]{};
{
"data": {
"Narray": {
"0":
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
"1":
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
}
}
Ideally you'd want Narray to be an actual JSON array, enclosed in [], with each element being another object, containing the property you need, like this:
{
"Narray": [
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
]
}
Then you can use jackson to decode the JSON string into a POJO structure. Once you have the objects, you can iterate over the array and retrieve the property you need into a list.
I assume that you only want to save each value of name into a String[] (string array), so you don't need to deserialize the JSON string to POJO, just use basic API to achieve what you want as follows:
BTW, your JSON string is invalid, you miss a right bracket.
ObjectMapper mapper = new ObjectMapper();
JsonNode nArray = mapper.readTree(jsonStr).get("data").get("Narray");
String[] nameList = new String[nArray.size()];
for (int i = 0; i < nArray.size(); i++) {
nameList[i] = nArray.get(String.valueOf(i)).get("name").asText();
}
System.out.println(Arrays.toString(nameList));
Console output:
[studio, venue]

Dynamic Json to CSV in java. looking for Generic code that works with any json, irrespective of any number of node in json file

hi i need to convert all json elements into csv . json is dynamic file, number of field and names will change from file to file.
i tried different methods but most cases i need to mention field names in scripts to pull data into csv
JSON file
[
{
"system": "Application",
"id": "12345",
"version": 1,
"event": "NEW",
"keywords": {
"ProductType": "ALL",
"Business": "USA",
},
"product": {
"type": "INS",
"startDate": 20190102,
"endDate": 20190104,
"cash": 100000.00,
"sub": {
"type": "Life",
"productId": 987,
"maturityDate": 20260421,
},
"paymentCalendar": [
"Monthly"
],
"duration": "20Y",
"Amount": 1000.00,
"cashFlows": [
{
"startDate": 20190102,
"endDate": 20190104,
"paymentDate": 20190104,
}
],
"principalFlows": [
{
"startDate": 20190102,
"endDate": 20190104,
"paymentDate": 20190102,
"currency": "USA",
"amount": 400.0
},
{
"startDate": 20190104,
"endDate": 20190104,
"paymentDate": 20190104,
"currency": "USA",
"amount": 600.0
}
]
},
"EventDate": 20190108,
"maturityDate": 20190104
}
]
above fields are not constant, all filed will keep changing.
expected output is below
Using Jackson ObjectMapper and Apache Commons CSV you can implement the functionality you require by reading the JSON and then visiting all the nodes.
If the node is a collection then visit all its children with the field or array index appended to the prefix
Note that arrays and objects need to be handled independently
If the node is a not a collection then add it to the CSV output
public void jsonToCsv(String json, Appendable appendable) throws IOException {
JsonNode root = new ObjectMapper().reader().readTree(json);
CSVPrinter printer = CSVFormat.DEFAULT.print(appendable);
appendNode(root.get(0), "", printer);
}
private void appendNode(JsonNode node, String prefix, CSVPrinter printer) throws IOException {
if (node.isArray()) {
for (int i = 0; i < node.size(); ++i) {
appendNode(node.get(i), String.format("%s/%d", prefix, i), printer);
}
} else if (node.isContainerNode()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
appendNode(field.getValue(), String.format("%s/%s", prefix, field.getKey()), printer);
}
} else {
printer.printRecord(prefix.substring(1), node.asText());
}
}

How to structure Multiple array of JSON in the beanshell sampler

How to structure Multiple array of JSON in the beanshell sampler
for example i need to pass N number of articles to a loop , so i have created a for loop to fetch the articles. here i have mentioned 3 articles as an example. but i need to fetch N number of articles in a loop.
The output should be like :
"itemLines": {
"itemLine": [
{
"bundleParentId": "",
"id": "1",
"itemType": "ART",
"itemNo": "1234",
},
{
"bundleParentId": "",
"id": "2",
"itemType": "ART",
"itemNo": "2021",
},{
"bundleParentId": "",
"id": "3",
"itemType": "ART",
"itemNo": "2023",
}
]
}
My code in the beanshell smpler is : For example here i have mentioned in the array list with 3 article numbers.
public void createJsonStructure() {
try
{
JSONObject rootObject = new JSONObject();
JSONArray articleArr = new JSONArray();
String[] article_list = {"00258882", "70234185", "00258882"};
log.info(article_list.length);
for (i=0;i<=article_list.length;i++)
{
JSONObject article_list= new JSONObject();
article_list.put("id", "i+1");
article_list.put("itemNo",article_list[i]);
article_list.put("requiredQty", "1");
articleArr.put(article_list);
}
log.info(articleArr);
rootObject.put("itemLines", articleArr);
log.info("rootObject is"+rootObject.toString(4));
props.put("JsonObjectoutput", rootObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
log.info("notes");
}
}
I could see the output is not retrieved in the jmeter logs . Here output should be printed in the logs , but i could see output is not printed.

Iterate last values present in a JSON response using java

I need to iterate and get the last values like name, url and color from below JSON response. Using java/gson api. Please help me on this.
{
"Title": {
"desc": [
{
"name": "PRE_DB",
"url": "http://jenkins.example.com/job/my_first_job/",
"color": "blue_anime"
},
{
"name": "SDD_Seller_Dashboard",
"url": "http://jenkins.example.com/job/my_second_job/",
"color": "blue_anime"
}
]
}
}
example output :
name : SDD_Seller_Dashboard
color :blue_anime
JSONObject data = new JSONObject(your_JSON_Repsonse);
JSONArray data_desc=data.getJSONArray(desc);
for(int i=0;i<=data_desc.length();i++)
{
name=data_desc.getString("name");
url=data_desc.getString("url");
color=data_desc.getString("color");
}

Accessing json string in java and creating hashmap Android

I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}

Categories

Resources