Create a new Json file then append other Json files to it - java

Need to create a new json file (combined.json) then append multiple json files (json1 and json2) to combined.json.
Example:
Json 1 - previously created json file
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
}
]
Json2 - previously created json file
[
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
Final product:
Combined.json - currenlty created json file
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]

Gson gson = new com.google.gson.Gson();
JSONArray combined = gson.fromJson(json1, JSONArray.class);
combined.addAll(gson.fromJson(json2, JSONArray.class));
// verify by looking on the value of: combined.toJSONString()

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"
}
]
}
}

Convert a CSV file with objects to JSON using Jackson

I have to convert JSON files into CSV and vice-versa, i use the Jackson library.
Going from JSON to CSV works well, for every type of data, including nested objects, but the counter way is much more harder, as the CSVMapper parse the CSV in a map, thus a couple .
Even if my actual works for simple CSV files, it doesn't for CSV that should produce JSON objects like this
JSON File
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
]
CSV file after the conversion
batters.batter[1].id;batters.batter[1].type;batters.batter[2].id;batters.batter[2].type;batters.batter[3].id;batters.batter[3].type;batters.batter[4].id;batters.batter[4].type;id;name;ppu;topping[1].id;topping[1].type;topping[2].id;topping[2].type;topping[3].id;topping[3].type;topping[4].id;topping[4].type;topping[5].id;topping[5].type;topping[6].id;topping[6].type;topping[7].id;topping[7].type;type
1001;Regular;1002;Chocolate;1003;Blueberry;1004;Devil's Food;0001;Cake;0.55;5001;None;5002;Glazed;5005;Sugar;5007;Powdered Sugar;5006;Chocolate with Sprinkles;5003;Chocolate;5004;Maple;donut
CSV to JSON converter
File csvFile = new File(CSV_File) ;
// Get the name of the file, for the new one in JSON
// String file_name = csvFile.getName().replaceFirst("[.][^.]+$", "");;
CsvMapper mapper = new CsvMapper();
mapper.disable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
CsvSchema schema = CsvSchema.emptySchema().withHeader(); // use first row as header; otherwise defaults are fine
MappingIterator<Map<String,String>> it = mapper.readerFor(Map.class)
.with(schema)
.readValues(csvFile);
// We extract a list from the mapping Iterator
List<Map<String, String>> readObjectsFromCsv = it.readAll() ;
// Clean the list
readObjectsFromCsv = cleanCSV(readObjectsFromCsv) ;
// Build the JSON file
try {
ObjectMapper mapperObject = new ObjectMapper() ;
// Write JSON formated data to output.json file
mapperObject.writerWithDefaultPrettyPrinter().writeValue(new File(JSON_File),readObjectsFromCsv);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The output of this code
[ {
"batters.batter[1].id" : "1001",
"batters.batter[1].type" : "Regular",
"batters.batter[2].id" : "1002",
"batters.batter[2].type" : "Chocolate",
"batters.batter[3].id" : "1003",
"batters.batter[3].type" : "Blueberry",
"batters.batter[4].id" : "1004",
"batters.batter[4].type" : "Devil's Food",
"id" : "0001",
"name" : "Cake",
"ppu" : "0.55",
"topping[1].id" : "5001",
"topping[1].type" : "None",
"topping[2].id" : "5002",
"topping[2].type" : "Glazed",
"topping[3].id" : "5005",
"topping[3].type" : "Sugar",
"topping[4].id" : "5007",
"topping[4].type" : "Powdered Sugar",
"topping[5].id" : "5006",
"topping[5].type" : "Chocolate with Sprinkles",
"topping[6].id" : "5003",
"topping[6].type" : "Chocolate",
"topping[7].id" : "5004",
"topping[7].type" : "Maple",
"type" : "donut"
} ]

Java Check Json contains sub json

Java - I have 2 json data which i am going to get from post and get calls.
How can i verify if Json 1 contains data of Json 2 ?
Json string 1
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
Json string 2
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
}

How to convert the tree structured json to Java object using gson

[
{
"sentence": "I want to buy shoes .",
"tree": {
"ROOT": [
{
"index": 2,
"token": "want",
"label": "VERB",
"pos": "VBP",
"tree": {
"nsubj": [
{
"index": 1,
"token": "I",
"label": "PRON",
"pos": "PRP"
}
],
"xcomp": [
{
"index": 4,
"token": "buy",
"label": "VERB",
"pos": "VB",
"tree": {
"aux": [
{
"index": 3,
"token": "to",
"label": "PRT",
"pos": "TO"
}
],
"dobj": [
{
"index": 5,
"token": "shoes",
"label": "NOUN",
"pos": "NNS"
}
]
}
}
],
"punct": [
{
"index": 6,
"token": ".",
"label": ".",
"pos": "."
}
]
}
}
]
}
}
]
This is tree represented in Json. But the keys for nested nodes keep changing.
For example "ROOT, nsubj, xcomp" ... etc.
How do I convert above json code to Java Object using gson.
Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use.
Thanks in advance.
Gson has a method Gson#fromJson. For example, this is a code to read a simple String object.
Gson gson = new Gson();
String str = gson.fromJson("\"hello\"", String.class);
System.out.println("String: " + str);
You need to prepare Java Object to read your proposed JSON. But, you don't need to write code by yourself. There is a website providing automatical JSON object generator.
jsonschema2pojo
enter following items:
Target language: Java
Source type: JSON
Annotation type: Gson
and enter your class name, for example "ParsedSentence"
then, write code. You will get object.
Gson gson = new Gson();
ParsedSentence parsed = gson.fromJson(longLongJsonString, ParsedSentence.class);

Create JSON data NVD3 Chart using Java

I working on NVD3 chart where need to create JSON data for chart as below:
[{
"key" : "North America" ,
"values" : [ [ 1025409600000 , 23.041422681023] , [ 1028088000000 , 19.854291255832] ]
},
{
"key" : "Africa" ,
"values" : [ [ 1025409600000 , 23.041422681023] , [ 1028088000000 , 19.854291255832] ]
},
{
"key" : "South America" ,
"values" : [ [ 1025409600000 , 23.041422681023] , [ 1028088000000 , 19.854291255832] ]
}]
Would somebody please help me create above JSON data using Java as I am trying to create this structure since last 3 hours not successful yet.
Here is the Plunker link: Stacked Area Chart NVD3
Here is the live JSON data example which I want to create in JAVA: JSON example data
Here is solution found by myself:
import org.json.JSONArray;
import org.json.JSONObject;
public class CreateNVD3JSONDataJava {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "North America");
JSONArray ja = new JSONArray();
ja.put(jo);
ja.put(jo);
ja.put(jo);
System.out.println(ja);
}
}
Edited code:
import org.json.JSONArray;
import org.json.JSONObject;
public class CreateNVD3JSONDataJava {
public static void main(String[] args) {
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "North America");
ja.put(jo);
jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "Africa");
ja.put(jo);
jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "South America");
ja.put(jo);
System.out.println(ja);
}
}
Output:
[
{
"values": [
[
1025409600000,
23
],
[
1028088000000,
19
],
[
1030766400000,
21
],
[
1033358400000,
22
]
],
"key": "North America"
},
{
"values": [
[
1025409600000,
23
],
[
1028088000000,
19
],
[
1030766400000,
21
],
[
1033358400000,
22
]
],
"key": "Africa"
},
{
"values": [
[
1025409600000,
23
],
[
1028088000000,
19
],
[
1030766400000,
21
],
[
1033358400000,
22
]
],
"key": "South America"
}
]

Categories

Resources