I need to create json string as per below using java: [duplicate] - java

This question already has answers here:
parsing json with java
(5 answers)
Closed 5 years ago.
I need to create json string as per below using java: under ADDTNLINFO element how to add multiple elements as Tag .could any one help please ?
{
"ADDTNLINFO":
{
"Tag":
{
"name": "a",
"value": "10"
},
"Tag":
{
"name": "a b",
"value": "20"
},
"Tag":
{
"name": "a b c",
"value": "30"
}
}
}

import com.google.gson.Gson;
List<Dto> beans = service.something();
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(beans);
You need to add Dependency for Google gson and it will according to your requirement

Related

JSON object is getting removed with remove method in JSON file instead of JSON array [duplicate]

This question already has answers here:
How to remove an element from JSON string in Java?
(2 answers)
Closed 6 months ago.
I am trying to remove JSON array from a JSON file using org.json library
I am trying to remove webAutomation JSON array from the JSON file as follows
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"webAutomation": [
{
"price": "500",
"courseTitle": "Selenium"
},
{
"price": "333",
"courseTitle": "Protractor"
}
],
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}
I tried following code. Here str has JSON file
JSONObject jsonObject = new JSONObject(str);
jsonObject.getJSONObject("courses").getJSONArray("webAutomation");
System.out.println("after removal");
String str2 = mapper.writeValueAsString(jsonObject);
System.out.println(str2);
This is removing the whole JSON object instead of just JSON Array.
The output is {"empty":false}
Please help
You can use remove method in org.json.JSONObject#remove.
JSONObject json = new JSONObject(str);
json.getJSONObject("courses").remove("webAutomation");
System.out.println(json);
The output will be:
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}

How to read specific json object element from the json array? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
I want to read only the 'home' phone number not 'fax' phone number from the phoneNumbers json array. I don't want to use indexing to get the 'home' phone number.
If you do not want to use indexing you could filter phoneNumbers array by property. Using JSONArray, JSONObject classes and Java 8 streams:
String json = Files.lines(Paths.get("src/main/resources/data.json")).collect(Collectors.joining());
JSONObject jsonObject = new JSONObject(json);
JSONArray phoneNumbers = jsonObject.getJSONArray("phoneNumbers");
String homeNumber = phoneNumbers.toList()
.stream()
.map(o -> (Map<String, String>) o)
.filter(stringStringMap -> stringStringMap.get("type").equals("home"))
.map(stringStringMap-> stringStringMap.get("number"))
.findFirst()
.orElse("unknown");
System.out.println(homeNumber);
This prints:
212 555-1234

Complicated Json parsing in java [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
i want to parse this code to get the id's location in an array.
Json is as follows:
"tipSecurableSet": {
"id": "082bdd09-6cff-41f9-a6f6-16a5bcc2eaa6",
"items": [
{
"typeId": "c5831702-15ed-483d-8253-c890e3f97dae",
"ids": [
"44b3efd4-5f7f-4698-aba4-1f4d9605c4eb"
],
"id": "b838aa0d-522a-411e-958a-41c711c6a856"
},
{
"typeId": "01c3c7de-2856-4665-90bc-a614caf335cd",
"ids": [
"8240a190-7e14-4ba4-87be-22febd09fa69"
],
"id": "62e62bf5-7a18-4518-a917-bb908d61fdd2"
}
]
}
}
You should take a look at Org.JSON library.
You can get the IDs very easily once you have your JSONObject. There are many ways to construct a JSONObject. You can parse XML.toJSONObject or use one of the JSONObject constructors.
JSONObject obj= new JSONObject(...);
Iterator<String> keys= obj.keys(); //Gets your Fields or Keys
To get the object for a key, here is an example with a String and an Array of JSONObjects.
String id= jsonArray.getJSONObject(i).getString("typeID")

Parse nested json from url and extract values from array using java [duplicate]

This question already has answers here:
Simplest way to read JSON from a URL in Java
(12 answers)
Closed 7 years ago.
I have a json url link which i would like to read its json response and extract values into variables so that i can use them later
{
"responseHeader": {
"status": 0,
"QTime": 4,
"params": {
"q": "*:*",
"facet.field": "TESTARRAY",
"indent": "true",
"rows": "0",
"wt": "json",
"facet": "true"
}
},
"response": {
"numFound": 12,
"start": 0,
"docs": []
},
"facet_counts": {
"facet_queries": {},
"facet_fields": {
"TESTARRAY": [
"JON",
22,
"SMITH",
34,
"ROBERT",
12
]
},
"facet_dates": {},
"facet_ranges": {},
"facet_intervals": {}
}
}
For extraction,I am using
JSONObject obj = new JSONObject(IOUtils.toString(new URL(jsonlink), Charset.forName("UTF-8")));
JSONArray arr = obj.getJSONArray("TEST_ARRAY");
Integer smithage=arr.get("SMITH");
So far this approach is not working.
What would be the best way to deal with it
Thanks in advance
TEST_ARRAY is not a top-level field, you need to dig down to get it, something like:
JSONObject obj = new JSONObject(IOUtils.toString(new URL(jsonlink), Charset.forName("UTF-8")));
JSONObject facet_counts = obj.getJSONObjecy("facet_counts");
JSONObject facet_fields = facet_counts.getJSONObjecy("facet_fields");
JSONArray test_array = obj.getJSONArray("TESTARRAY");
Integer smithage = test_array.getInt(3);

How to extract a specific link in a json file [duplicate]

This question already has answers here:
How to parse JSON file?
(3 answers)
Closed 8 years ago.
"papers": [
{
"files": [
{
"url": "http://farnsworth.papro.org.uk/file/977",
"type": "Initial XML version of the paper",
"name": "c6938201-dac0-4ef9-91cd-ca6e8c30f4b8.xml"
},
{
"url": "http://farnsworth.papro.org.uk/file/978",
"type": "Final annotated XML file",
"name": "c6938201-dac0-4ef9-91cd-ca6e8c30f4b8_final.xml"
}
]
How can i get the first url in this json file ? What I have so far is:
JSONObject file = (JSONObject) files.get(j);
String url = (String) file.get("url");
System.out.println(url);
something like this should work :
JSONArray results = d.getJSONArray("files");
JSONObject p = (JSONObject)results.get(0);
url = p.getString("url");

Categories

Resources