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().
Related
I need to remove the outermost element(ns0:TableData) from the below JSON paylaod.
{
"ns0:TableData": {
"descr": 111,
"note": 11,
"kpar": 1111,
"karr": 111,
"xmlns:ns0": "urn:it:alia:inaz",
"codice": 1,
"dend": 1111,
"anz_app_a": 1,
"dini": 11
}
}
I am using the below code to covert the incoming XML to JSON
String inputData = IOUtils.toString(inputstream);
System.out.println(inputData);
JSONObject xmlJSONObj = XML.toJSONObject(inputData);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
In XPath 3.1, use json-doc('input.json')?*
Try this example
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.ToString;
public class Main {
#Data
#ToString
private static class All {
#JsonProperty("descr")
int descr;
int note;
int kpar;
int karr;
#JsonProperty("xmlns:ns0")
String xmlnsNs0;
int codice;
int dend;
#JsonProperty("anz_app_a")
int anzAppA;
int dini;
}
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String json = "{\n" //
+ " \"ns0:TableData\": {\n" //
+ " \"descr\": 111,\n" //
+ " \"note\": 11,\n" //
+ " \"kpar\": 1111,\n" //
+ " \"karr\": 111,\n" //
+ " \"xmlns:ns0\": \"urn:it:alia:inaz\",\n" //
+ " \"codice\": 1,\n" //
+ " \"dend\": 1111,\n" //
+ " \"anz_app_a\": 1,\n" //
+ " \"dini\": 11\n" //
+ " }\n" //
+ "}\n"
+ "";
ObjectMapper obj = new ObjectMapper();
JsonNode jstree = obj.readTree(json);
JsonNode data = jstree.get("ns0:TableData");
All a = obj.readValue(data.toString(), All.class);
System.out.println(a);
}
}
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();
}
}
}
When I use the parser from org.json.simple.parser.* I get an exception whenever one of the values in JSON contains a space. For example:
{"name":"Adam"}
would parse correctly, but
{"name":"Ad am"}
would cause "unexpected token END OF FILE at position 11" exception
Here is the code that I use to convert a JSON string into a JSONObject.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringJSON);
Try to get through this below example and each value contains space except integer one and giving this example just because of you don't have shared your source code.
JSON File(personal_detail.json):
{
"name":"arif mustafa",
"age":26,
"address":["district is Korba","state is Chhattisgarh","country is India"]
}
Java source to read the JSON file format:
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 JSONExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/resources/personal_detail.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject + "\n");
String name = (String) jsonObject.get("name");
System.out.println("name : " + name);
long age = (Long) jsonObject.get("age");
System.out.println("age : " + age);
//get Object loop array
JSONArray address = (JSONArray) jsonObject.get("address");
System.out.println("address is : ");
Iterator<String> iterator = address.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I like to get the value of code from below JSON but I am getting an error like below:-
java.lang.NullPointerException
I am getting an error in below line of code
Iterator<String> iterator = companyList.iterator();
I have JSON object like below:-
{
"products":
{
"productsApp13": {
"code": "productsApp13",
"name": "productsApp13",
"attribute_set": "Apparel",
"product_type": "product",
"status": "active"
}
}
}
My code:-
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
try {
Object obj1 = parser.parse(new FileReader(path.directorypath));
JSONObject jsonObject = (JSONObject) obj1;
String name = (String) jsonObject.get("products").toString();
System.out.println("Testing Parse Value = "+name);
request.payload = name;
JSONArray companyList = (JSONArray) jsonObject.get("code");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
I know that productsApp13 or code key is not an array while I am not able to identify any method to read this particular value.
Moreover, I also want to know that how can I modify this value for my payload
This minimal example works for me:
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import java.io.StringReader;
public class Main {
public static void main(String[] args) {
final JsonReader jsonReader = Json.createReader(new StringReader("{\n" +
" \"products\":\n" +
" {\n" +
" \"productsApp13\": {\n" +
" \"code\": \"productsApp13\",\n" +
" \"name\": \"productsApp13\",\n" +
" \"attribute_set\": \"Apparel\",\n" +
" \"product_type\": \"product\",\n" +
" \"status\": \"active\"\n" +
" }\n" +
" }\n" +
"}"));
final JsonObject jsonObject = jsonReader.readObject();
final JsonValue products = jsonObject.get("products");
final JsonValue productsApp13 = ((JsonObject) products).get("productsApp13");
final JsonValue code = ((JsonObject) productsApp13).get("code");
System.out.println("code = " + code); // code = "productsApp13"
}
}
To get access to javax.json.* I use the Maven dependency
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
try following hope it fix your problem
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.json.JSONObject;
public class Main {
public static void main(final String[] args) throws Exception {
final JSONObject jsonObject = new JSONObject(getResponseAsString(getFilePath()));
final JSONObject products = jsonObject.getJSONObject("products");
final String name = products.toString();
System.out.println("Testing Parse Value = " + name);
final JSONObject productsApp13 = products.getJSONObject("productsApp13");
final String code = productsApp13.getString("code");
System.out.println("code value : " + code);
}
private static Path getFilePath() throws URISyntaxException, FileNotFoundException {
URL url = Main.class.getClassLoader().getResource("jsonFile.txt");
if (url == null) {
throw new FileNotFoundException();
}
return Paths.get(url.toURI());
}
private static String getResponseAsString(final Path filePath) throws FileNotFoundException, IOException {
return new String(Files.readAllBytes(filePath));
}
}
Maven dependency to compile above
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
</dependency>
Code worked for me:-
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONObject jsonObject1 = (JSONObject) jsonObject.get("products");
JSONObject jsonObject2 = (JSONObject)jsonObject1.get("productsApp15");
String firstName = (String) jsonObject2.get("code").toString();
When jsonobject is converted to String or long it returns null. Why?
My JSON file:
{
"memberships": [
{
"project": {
"id": 30483134480107,
"name": "Asana Integrations"
},
"section": null
}
]
}
And my code:
package jsontest;
import java.beans.Statement;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class MoreComplexJson {
private static final String filePath = "C:\\jsonTestFile.json";
public static void main(String[] args) {
try {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray memberships = (JSONArray) jsonObject.get("memberships");
for (int z = 0; z < memberships.size(); z++) {
Iterator m = memberships.iterator();
// take each value from the json array separately
while (m.hasNext()) {
JSONObject innerObj = (JSONObject) m.next();
Long id = (Long) innerObj.get("id");
String name = (String) innerObj.get("name");
System.out.println("id " + id + " with name " + name);
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
System.out.println(ex + "");
}
catch (IOException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
catch (ParseException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
catch (NullPointerException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
}
}
The output:
id null with name null
id and name belongs to the project JSONObject so get those two values using the project JSONObject
Try this for loop
for (int z = 0; z < memberships.size(); z++) {
JSONObject m = (JSONObject) memberships.get(z);
JSONObject innerObj = (JSONObject) m.get("project");
// If you want section
String section = (String) m.get("section");
System.out.println("section " + section);
Long id = (Long) innerObj.get("id");
String name = (String) innerObj.get("name");
System.out.println("id " + id + " with name " + name);
}
The problem is that when you are trying to get id and name you're not taking it from project but from object that contains project. There should be:
JSONObject innerObj = (JsonObject) ((JSONObject) m.next()).get("project)";
This kind of code can get pretty ugly pretty fast. Instead you could use a higher order parser, such as Jackson. Then your code can be much cleaner and you don't have to worry about digging into the conversion of each piece of JSON.