My code :
{
"_id" : {
"countryId" : 1,
"countryName" : "Hong Kong"
},
"cities" : [
{
"cityId" : 1,
"cityName" : "Hong Kong",
"sites" : [
{
"siteId" : 1,
"siteName" : "Kong Centre"
}
]
}
]
}
This is the sample json. I am working on a project where i have to get sites based on countries and cities. I am able to set country id and country name in my java custom object but unable to fetch "cities" & "sites" embedded array. Please assist.
This is the way you can find out cities and sites data using JSOnObject and JSONArray.
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonRead {
public static void main(String args[]) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:\\Users\\aq104e\\Desktop\\text.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArrayOfCities = (JSONArray) jsonObject.get("cities");
for (Object jsonObjectOfCities : jsonArrayOfCities) {
JSONObject city = (JSONObject) jsonObjectOfCities;
String cityid = String.valueOf(city.get("cityId"));
JSONArray jsonArrayOfSites = (JSONArray) city.get("sites");
for (Object jsonObjectOfSites : jsonArrayOfSites) {
JSONObject jsonLineItem = (JSONObject) jsonObjectOfSites;
String siteId = String.valueOf(jsonLineItem.get("siteId"));
String siteName = String.valueOf(jsonLineItem.get("siteName"));
System.out.println("site Id is " + siteId);
System.out.println("siteName is " +siteName);
}
String cityName = (String) city.get("cityName");
System.out.println("City id -> " + cityid);
System.out.println("city name is -> " + cityName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
Pls help me to understand why this java program doesn't find array from json file. I didn't find similar type json file via google so pls educate me.
Error:
C:\temp\example.json
org.json.JSONException: JSONObject["result"] not found.
at org.json.JSONObject.get(JSONObject.java:572)
at org.json.JSONObject.getJSONArray(JSONObject.java:765)
at JsonParsingMachine.main(JsonParsingMachine.java:17)
.java content:
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.json.*;
public class JsonParsingMachine {
public static void main(String[] args) {
String tiedosto = "C:/temp/example.json";
System.out.println(Paths.get(tiedosto));
try {
String contents = new String((Files.readAllBytes(Paths.get(tiedosto))));
JSONObject o = new JSONObject(contents);
JSONArray res = o.getJSONArray("result");
for (int i = 0; i < res.length(); i++) {
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
json file (example.json)
{
"quoteResponse" : {
"result" : [ {
"language" : "en-US",
"region" : "US",
"quoteType" : "EQUITY",
"quoteSourceName" : "Nasdaq Real Time Price",
"triggerable" : true
} ]
}
}
result array is inside quoteResponse JSONObject. You need to do this instead:
JSONObject o = new JSONObject(contents);
JSONObject quoteResponse = o.getJSONObject("quoteResponse");
JSONArray res = quoteResponse.getJSONArray("result");
I have a JSON file i.e test.json.
{
"Added": {
"type": "K",
"newmem": {
"IDNew": {
"id": "777709",
"type": "LOP"
},
"birthDate": "2000-12-09"
},
"code": "",
"newest": {
"curlNew": "",
"addedForNew": ""
}
}
}
I tried the following code :
File file = new File("test.json");
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader(file.getAbsolutePath()
));//path to the JSON file.
System.out.println(data.toString());
JSONObject jObject = new JSONObject();
jObject.put("id","12345678");
System.out.println(jObject);
Result getting :-
{
"Added": {
"type": "K",
"newmem": {
"IDNew": {
"id": "777709",
"type": "LOP"
},
"birthDate": "2000-12-09"
},
"code": "",
"newest": {
"curlNew": "",
"addedForNew": ""
}
}
}{
"id":"12345678"
}
Value id: "777709" is not getting updating to id:"12345678" but it's adding at last. Please help me to and tell me how to replace the id value.
You can try this with simple json library(library) . I am separately printed all object for understanding. AS you declare Id object inside two more object, so firstly you have to get this object then get your desire object IDNew. Then put new id value in id field.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Main {
private static final String filePath = "E:\\project-test\\scloud\\test\\src\\main\\resources\\test";
public static void main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
JSONObject addedObj = (JSONObject) jsonObject.get("Added");
System.out.println("Added is: " + addedObj);
JSONObject newmemObject =(JSONObject) addedObj.get("newmem");
System.out.println("newmemObject is: " + newmemObject);
JSONObject idNewObj =(JSONObject) newmemObject.get("IDNew");
System.out.println("IdNewObj is: " + idNewObj);
long id =Long.valueOf((String) idNewObj.get("id"));
System.out.println(id);
idNewObj.put("id",809809809);
System.out.println(jsonObject);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
Or for simplicity you can use this
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
JSONObject idObj = (
(JSONObject) (
(JSONObject) (
(JSONObject)
jsonObject.get("Added")
).get("newmem")
).get("IDNew")
);
idObj.put("id", 98009809);
System.out.println("After ID value updated : "+jsonObject);
You can update a nested element in a JSONObject using the simple-json java lib as follows:
JSONObject added = (JSONObject) data.get("Added");
JSONObject newmem = (JSONObject) added.get("newmem");
JSONObject idNew = (JSONObject) newmem.get("IDNew");
idNew.put("id","12345678");
System.out.println(data);
One more solution using different library json-path:
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
#Test
public void exampleToReplaceSingleElement_jsonTakenFromFile() throws IOException {
String expectedId = "12345678";
String expectedJson = "{\n" +
" \"Added\": {\n" +
" \"type\": \"K\",\n" +
" \"newmem\": {\n" +
" \"IDNew\": {\n" +
" \"id\": \"12345678\",\n" +
" \"type\": \"LOP\"\n" +
" },\n" +
" \"birthDate\": \"2000-12-09\"\n" +
" },\n" +
" \"code\": \"\",\n" +
" \"newest\": {\n" +
" \"curlNew\": \"\",\n" +
" \"addedForNew\": \"\"\n" +
" }\n" +
" }\n" +
"}";
Configuration configuration = Configuration
.builder()
.options(Option.SUPPRESS_EXCEPTIONS)
.build();
File json = new File("src/test/resources/test.json");
System.out.println(json.getAbsolutePath());
DocumentContext parsed = JsonPath.using(configuration).parse(json);
parsed.set("$.Added.newmem.IDNew.id", expectedId);
String actual = parsed.jsonString();
log.info("After ID value updated: {}", actual);
assertThat(actual).isEqualToIgnoringWhitespace(expectedJson);
}
Examples also accessible on get test exampleToReplaceSingleElement() or test exampleToReplaceSingleElement_jsonTakenFromFile().
I have a JSON file with following data:
{ "data" : [
{ "ID":"3b071d17-bfe5-4474-a7b4-58c755c7d954",
"value":"328.0"},
{ "ID":"dc4607f9-5955-4dd8-8c1a-abd3719edb6f",
"value":"764.1"},
{ "ID":"a4aa9f3b-599f-4815-5776-20fa38b064b5",
"value":"983.6"},
{ "ID":"c6fb7cd8-381d-93fa-711b-9482ab394ffa",
"value":"351.5"},
{ "ID":"2366a36b-8df2-72db-40bc-bbbe3258f09c",
"value":"539.3"}
]}
How can get the data range from ID dc4607f9-5955-4dd8-8c1a-abd3719edb6f (2nd) to c6fb7cd8-381d-93fa-711b-9482ab394ffa (4th) or to last data? Is it possible to do so?
Here's my attempt:
List<float> dataSave = new ArrayList();
try {
JSONObject objectFromFile = ...; //JSONReadFile
JSONArray dataArray = objectFromFile.getJSONArray("data");
//here will get data from the start ID to end ID
dataSave.add((float)dataArray.getDouble("value");
} catch (JSONException e) {
e.printStackTrace();
}
If i understood correctly you want get the values of the json array starting with the start id and stopping on the end id. both limits are included.
I am pretty sure that there must be a better way but here is my example if it helps you:
convertJsonArrayToMap: generates a map from the JsonArray
getValueBasedOnRange: saves the value of the json object with id startId until endId
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class App
{
static String data = "{ \"data\" : [\r\n" +
" { \"ID\":\"3b071d17-bfe5-4474-a7b4-58c755c7d954\",\r\n" +
" \"value\":\"328.0\"},\r\n" +
" { \"ID\":\"dc4607f9-5955-4dd8-8c1a-abd3719edb6f\",\r\n" +
" \"value\":\"764.1\"},\r\n" +
" { \"ID\":\"a4aa9f3b-599f-4815-5776-20fa38b064b5\",\r\n" +
" \"value\":\"983.6\"},\r\n" +
" { \"ID\":\"c6fb7cd8-381d-93fa-711b-9482ab394ffa\",\r\n" +
" \"value\":\"351.5\"},\r\n" +
" { \"ID\":\"2366a36b-8df2-72db-40bc-bbbe3258f09c\",\r\n" +
" \"value\":\"539.3\"}\r\n" +
"]}";
public static void main(String... args){
JsonParser jsonParser = new JsonParser();
JsonObject objectFromString = jsonParser.parse(data).getAsJsonObject();
JsonArray dataArray= objectFromString.getAsJsonArray("data");
//here will get data from the start ID to end ID
Set<Entry<String, Float>> dataMap = convertJsonArrayToMap(dataArray);
String startId = "dc4607f9-5955-4dd8-8c1a-abd3719edb6f";
String endId = "c6fb7cd8-381d-93fa-711b-9482ab394ffa";
List<Float> dataSave = getValueBasedOnRange(startId, endId,dataMap);
System.out.println(dataSave.toString());
}
//Generate and return the map from the JsonArray parameter
private static Set<Entry<String, Float>> convertJsonArrayToMap(JsonArray dataArray){
Map<String,Float> dataMap = new LinkedHashMap<>();
for (JsonElement currentElement : dataArray) {
JsonObject currentJsonObject = currentElement.getAsJsonObject();
dataMap.put(currentJsonObject.get("ID").getAsString(), currentJsonObject.get("value").getAsFloat());
}
return dataMap.entrySet();
}
//Generate and return the List<Float> from the map parameter
//Save the float value of the object with ID=startId
//Save the float value of the ANY object after startID
//Save the float value of the object with ID=endId and return
private static List<Float> getValueBasedOnRange(String startId, String endId, Set<Entry<String, Float>> dataMap){
boolean collectFlag = false;
List<Float> dataSave = new ArrayList<>();
for(Entry<String, Float> mapEntry : dataMap) {
if(startId.equals(mapEntry.getKey())) {
collectFlag = true;
}
if(collectFlag) {
dataSave.add(mapEntry.getValue());
}
if(endId.equals(mapEntry.getKey())) {
return dataSave;
}
}
return dataSave;
}
I hope it helps.
I have JSONArray in String format as follows :
{
"productsList": [{
"map": {
"productSubcategory": "Levensverzekering",
"nameFirstInsured": "Akkerman"
}
},
{
"map": {
"productSubcategory": "Lineair dalend",
"nameFirstInsured": "Akkerman"
}
}
]
}
I want to convert this String as follows :
{
"productsList": [{
"productSubcategory": "Levensverzekering",
"nameFirstInsured": "Akkerman"
},
{
"productSubcategory": "Lineair dalend",
"nameFirstInsured": "Akkerman"
}
]
}
I have converted JSONArray to String so need operation as on the String on provided String in JSON format.
How I can change the String as required? What should I put in jsonString.replaceAll("","") function?
There is no easy way to do this, you have to do something like this.
OUTPUT IS:
{
"productsList":[
{
"productSubcategory":"Levensverzekering",
"nameFirstInsured":"Akkerman"
},
{
"productSubcategory":"Lineair dalend",
"nameFirstInsured":"Akkerman"
}
]
}
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class test {
public static void main(String[] args) throws IOException, InterruptedException {
JSONParser parser = new JSONParser();
JSONObject newObj = new JSONObject();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arr = (JSONArray) jsonObject.get("productsList");
JSONArray newArr = new JSONArray();
for(int i = 0 ; i < arr.size();i++){
JSONObject object = (JSONObject) arr.get(i);
JSONObject a = (JSONObject) object.get("map");
newArr.add(a);
}
newObj.put("productsList", newArr);
System.out.println(newObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using org.json for this.
This is my application for generating a JSON structure
package com;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws JSONException {
Test testJson = new Test();
Map<String, LinkedList<String>> categoryitemslistMap = new LinkedHashMap<String, LinkedList<String>>();
JSONObject leafobj = new JSONObject();
JSONArray T2Array = new JSONArray();
JSONArray T3Array = new JSONArray();
JSONArray T4Array = new JSONArray();
JSONObject T3JsonObj = new JSONObject();
JSONObject T2JsonObj = new JSONObject();
LinkedList<String> T3ValuesList = new LinkedList<String>();
T3ValuesList.add("Bottled");
T3ValuesList.add("Fountain");
categoryitemslistMap.put("Soft Drinks", T3ValuesList);
String t2consildated_Data = "Lemon,Orange";
for (Map.Entry<String, LinkedList<String>> entry : categoryitemslistMap.entrySet()) {
String t1data = entry.getKey();
if (t1data.equalsIgnoreCase("Soft Drinks")) {
LinkedList<String> t1ChildList = entry.getValue();
for (String t2Data : t1ChildList) {
if (t2consildated_Data != null&& !t2consildated_Data.isEmpty()) {
StringTokenizer stt = new StringTokenizer(t2consildated_Data, ",");
while (stt.hasMoreTokens()) {
String t3data = stt.nextToken();
JSONArray jsonarray = testJson.createLeaf();
leafobj.put("leaf", jsonarray);
T4Array.put(leafobj);
}
}
}
} // end of processing values of categoryitemslistMap(Linked List)
} // end of processing categoryitemslistMap
T3JsonObj.put("T3",T4Array);
System.out.println(T3JsonObj);
} // end of main method
public JSONArray createLeaf() throws JSONException {
JSONArray ja = new JSONArray();
for(int i=0;i<2;i++)
{
if(i==0)
{
JSONObject jo = new JSONObject();
jo.put("name", "500 ML");
ja.put(jo);
}
else if(i==1)
{
JSONObject jo = new JSONObject();
jo.put("name", "1 Litre");
ja.put(jo);
}
}
return ja;
}
}
With this the output is being genrated as
{"T3":[{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]},{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]},{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]},{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]}]}
Could anybody please tell me how can i generate the following JSON Structure ?
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
},
{
"name": "Orange",
"leaf": [
{
"name": "500 ML"
}
]
}
]
},
{
"name": "Fountain",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
},
{
"name": "Orange",
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
}
From the Javadocs:
So just replace System.out.println(T3JsonObj); with System.out.println(T3JsonObj.toString(4));