Remove outermost node from the JSON payload - java

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);
}
}

Related

Simple java questionnaire using json

I made a simple questionnaire. I need to write the responses to a JSON file. How to do it?
I use IDEA Intellij and library GSON for work with JSON.
This is main class "Quiz":
package questions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Scanner;
public class Quiz {
public static <Outfile> void main(String[] args) throws IOException {
String userJson = "[{\"question\": \"1.What is your marital status?\", \"a\": \"(a)Single\", \"b\": \"(b)Married\"}," +
"{\"question\": \"2.Are you planning on getting married next year?\", \"a\": \"(a)Yes\", \"b\": \"(b)No\"},"+
"{\"question\": \"3.How long have you been married?\", \"a\": \"(a)Less than a year\", \"b\": \"(b)More than a year\"},"+
"{\"question\": \"4.Have you celebrated your one year anniversary?\", \"a\": \"(a)Yes\" , \"b\": \"(b)No\"}]";
Gson gson = new Gson();
Type questionListType = new TypeToken<ArrayList<Question>>(){}.getType();
ArrayList<Question> questionArray = gson.fromJson(userJson, questionListType);
FileWriter fileWriter = new FileWriter("answer.json");
for(Question question : questionArray) {
System.out.println("Question:" + question.question);
System.out.println("Answer:" + question.a + " " + question.b);
Scanner keyboardInput = new Scanner(System.in);
String answer = keyboardInput.nextLine();
System.out.println("You got: " + answer);
}
}}
This is class "Question":
package questions;
public class Question {
public String question;
public String a;
public String b;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setAnswer2(String b) {
this.b = b;
}
}
I'm trying to use FileWriter, but I'm doing it wrong. The output file is empty. Help me, pls.
You have created a FileWriter, but you are never actually writing anything to the file. This is why the file is empty.
string jsonData = "{}";
FileWriter output = new FileWriter("answer.json");
// Writes the string to the file
output.write(jsonData);
// Closes the writer
output.close();
This would allow you to write contents to a file. Make sure to call close() on the FileWriter after writing your content. After that your file answer.json should contain:
{}
#Test
public void test1() {
try {
String userJson = "[{\"question\": \"1.What is your marital status?\", \"a\": \"(a)Single\", \"b\": \"(b)Married\"}," +
"{\"question\": \"2.Are you planning on getting married next year?\", \"a\": \"(a)Yes\", \"b\": \"(b)No\"}," +
"{\"question\": \"3.How long have you been married?\", \"a\": \"(a)Less than a year\", \"b\": \"(b)More than a year\"}," +
"{\"question\": \"4.Have you celebrated your one year anniversary?\", \"a\": \"(a)Yes\" , \"b\": \"(b)No\"}]";
JSONArray jsonArray = JSON.parseArray(userJson);
System.out.println(jsonArray);
List<Question> javaList = jsonArray.toJavaList(Question.class);
writeToFile(javaList);
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeToFile(List<Question> data) throws Exception {
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter("D:\\test.txt"));
for (int i = 0; i < data.size(); i++) {
bw.write(JSON.toJSONString(data.get(i)));
bw.newLine();
bw.flush();
}
bw.close();
} catch (Exception e) {
throw e;
}
}

Converting JSON string to Map with custom types

My JSON string is like this:
{
"100": {
"mode": 100,
"enabled": true,
"value": "someString"
},
"101": {
"mode": 101,
"enabled": false,
"value": "someString"
}
}
I have a class actually
class Mode {
#JsonProperty("mode")
long mode;
#JsonProperty("enabled")
boolean enabled;
#JsonProperty("value")
String value;
}
I tried
objectMapper.readValue(jsonString, Map.class);
But its generic map and also the numbers are converted to Integer types not Long. Using Mode in place of Map above throws exception.
How to get Long in generic Map?
And, how can I get a Map<String, Mode> out of the json string?
I have got jackson library in my projects maven.
your Key is String . It will work for you .
TypeReference<HashMap<String, Mode>> typeRef = new TypeReference<HashMap<String, Mode>>() {};
Map<String,Mode> map = objectMapper.readValue(jsonString,typeRef);
Updated :
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Mode {
#JsonProperty("mode")
long mode;
#JsonProperty("enabled")
boolean enabled;
#JsonProperty("value")
String value;
#Override
public String toString() {
return "Mode{" +
"mode=" + mode +
", enabled=" + enabled +
", value='" + value + '\'' +
'}';
}
public static void main(String[] args) throws IOException {
String json = "{\n"
+ " \"100\": {\n"
+ " \"mode\": 100,\n"
+ " \"enabled\": true,\n"
+ " \"value\": \"someString\"\n"
+ " },\n"
+ " \"101\": {\n"
+ " \"mode\": 101,\n"
+ " \"enabled\": false,\n"
+ " \"value\": \"someString\"\n"
+ " }\n"
+ "}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<HashMap<String, Mode>> typeRef = new TypeReference<HashMap<String, Mode>>() {
};
Map<String, Mode> map = objectMapper.readValue(json, typeRef);
map.entrySet().forEach(entry-> System.out.println(entry.getKey() + " : " +entry.getValue() ));
}
}
Output :
100 : Mode{mode=100, enabled=true, value='someString'}
101 : Mode{mode=101, enabled=false, value='someString'}

How to replace value in json file

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().

Get specific data range from JSON file

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.

How to retrieve value from JSON using java

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();

Categories