I'm using the org.json.simple.JSONObject library to read some text and form it into JSON.
The code I have is as follows:
public class PerfMetrics {
private static String filePath = "Shell_Pricing_Metrics.json";
private static String jsoncontent;
public static void clearFileContents(String filePath) throws IOException {
File f1 = new File(filePath);
new FileWriter(f1);
}
public static void metricAsJSON(String testName, long testTime) {
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
JSONObject obj = new JSONObject();
obj.put("testname", testName);
obj.put("Duration", testTime);
obj.put("Timestamp", ts.toString());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(obj.toJSONString());
jsoncontent = gson.toJson(je);
JsonArray jsonArray = new JsonArray();
jsonArray.add(je);
jsoncontent = gson.toJson(jsonArray);
}
public static void writeJsonToFile() {
try {
File f1 = new File(filePath);
if (!(f1.exists())) {
f1.createNewFile();
}
FileWriter fw1 = new FileWriter(f1, true);
PrintWriter pw1 = new PrintWriter(fw1);
if (f1.exists() && f1.isFile()) {
pw1.println(jsoncontent);
pw1.flush();
pw1.close();
fw1.close();
} else {
System.out.println("Please provide a valid path to destination Json file");
}
} catch(Exception e){
e.printStackTrace();
}
}
}
Writes to a file as:
[
{
"Duration": 30,
"testname": "Upload Data click to Model Prices dropdown display time:",
"Timestamp": "2019-10-15 09:47:53.804"
}
]
I need the data as:
[
{
"testname": "Shopping dropdown display time:",
"Duration": 2156,
"Timestamp": "2019-10-10 14:29:01.945"
},
{
"testname": "Clothing dropdown display time:",
"Duration": 3567,
"Timestamp": "2019-10-10 14:30:01.534"
},
{
"testname": "Electrical dropdown display time:",
"Duration": 2098,
"Timestamp": "2019-10-10 14:33:01.532"
},
{
"testname": "Toys dropdown display time:",
"Duration": 4562,
"Timestamp": "2019-10-10 14:35:01.435"
}
]
I can get around this clunkily with my limited Java skills but wondered what is the best library / practice to support the transformation of the object strings into a Json Array?
It looks like you're using the function once per JSONObject, and writing the file each time - if that's the case then you could instead return the JSONObject from that method:
/*... obj.put(key, value); obj.put('Timestamp') ... */
return obj;
And then where you call .metricAsJSON now, append it to a JSONArray object like so:
JSONArray arr = new JSONArray();
for (... metric in some other array ...) {
JSONObject obj = GetMetrics.metricAsJSON(key, value);
arr.put(obj);
}
String jsonString = arr.toString();
/* Write jsonString to file */
If you need to add values dynamically and write multiple times, you could store the JSONArray as a method variable, or load the file into a JSONArray object each time you need to append something to the end.
You need to do this
public class GetMetrics {
public static void clearFileContents(String filePath) throws IOException {
File f1 = new File(filePath);
new FileWriter(f1);
}
public static void metricAsJSON(String key, long value, String filePath) {
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
JSONObject obj = new JSONObject();
obj.put(key, value);
obj.put("Timestamp", ts.toString());
try {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(obj.toJSONString());
String jsoncontent = = gson.toJson(je);
File f1 = new File(filePath);
if (!(f1.exists())) {
f1.createNewFile();
}
FileWriter fw1 = new FileWriter(f1, true);
PrintWriter pw1 = new PrintWriter(fw1);
if (f1.exists() && f1.isFile()) {
pw1.println(jsoncontent);
pw1.flush();
pw1.close();
fw1.close();
} else {
System.out.println("Please provide a valid path to destination Jsonfile");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is my code for the parsing the JSON file and printing too.:
public class JsonpJsonParser implements IparseJson {
public static void main(String[] args) {
IparseJson parser = new JsonpJsonParser();
try (FileInputStream in = new FileInputStream("data.json")) {
List<QueryResultBean1> results = parser.parseJson(in);
for (QueryResultBean1 result : results) {
System.out.println(result.getHeader().getRequest_id());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public List<QueryResultBean1> parseJson(InputStream in) {
JsonReader reader = Json.createReader(in);
JsonObject json = reader.readObject();
reader.close();
// parse the json object, return something
List<QueryResultBean1> results = new ArrayList<QueryResultBean1>();
JsonArray items = json.getJsonArray("header");
for (JsonValue item : items) {
if (item instanceof JsonObject) {
QueryResultBean1 result = createBean((JsonObject)item);
results.add(result);
}
}
return results;
}
public QueryResultBean1 createBean(JsonObject json) {
QueryResultBean1 bean = new QueryResultBean1();
// you could also change tags to a List
JsonArray array = json.getJsonArray("header");
String[] h1 = new String[array.size()];
for (int i = 0; i < h1.length; i++) {
h1[i] = array.getString(i);
}
bean.setTags(h1);
retrun bean}
Ive tried executing this code for the JSON file:
"header":[
{
"request_id":1547706529870,
"file_name":"Sm-1547706529870.xlsm",
"file_type":"CIR",
"status":"NEW",
"is_end":false
}
GOT THE ERROR AS:
`Exception in thread "main" java.lang.NullPointerExceptionat com.example.webjson.com.webjson.p1.JsonpJsonParser.createBean(JsonpJsonParser.java:60)
NEED HELP TO PARSE THE DATA.JSON FILE IN JAVA
In the code below:
JsonArray array = json.getJsonArray("header");
You are trying to retrieve an JsonArray from String?, you should retrieve the element in array using an index like:
JsonArray array = json.getJsonArray(0);
Here is code of my getStream method:
public static Twitch_Stream getStream(String channelname) {
try {
String json = API.readJsonFromUrl("https://api.twitch.tv/kraken/streams?channel=" + channelname);
Twitch_Stream stream = new Twitch_Stream();
if (json.equalsIgnoreCase("[]")) {
stream.setOnline(false);
return stream;
}
JsonArray jb = gson.fromJson(json, JsonArray.class);
if (jb.size() != 0) {
JsonObject jo = (JsonObject) jb.get(0);
stream.setOnline(true);
stream.load(jo);
}
return stream;
} catch (Exception error) {
error.printStackTrace();
}
return null;
}
and here is code of Twitch_Stream class http://pastebin.com/3RX1L1cv
When I make something like this
Twitch_Stream streamer = Twitch_API.getStream("Jankos");
Bukkit.broadcastMessage("getName " + streamer.getName());
Bukkit.broadcastMessage(streamer.isOnline() + "");
streamer.getName() return null and streamer.isOnline() returns false, even when stream is on.
Where did I make a mistake?
I don't know what problem is in your code but simple workaround would be reading content from "https://api.twitch.tv/kraken/streams/" + channel which is JSON in format:
{
"_links" : {
//links to stream and channel
},
"stream" : {
//details about current stream
}
}
Now if value of stream key is null stream is off-line. If it is not null, it is on-line.
So your code can look like
public static void main(String[] argv) throws IOException {
System.out.println(checkIfOnline("Jankos"));
System.out.println(checkIfOnline("nightblue3"));
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel;
String jsonText = readFromUrl(channerUrl);// reads text from URL
JSONObject json = new JSONObject(jsonText);
return !json.isNull("stream");
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
try (Stream<String> stream = new BufferedReader(new InputStreamReader(
page.openStream(), StandardCharsets.UTF_8)).lines()) {
return stream.collect(Collectors.joining(System.lineSeparator()));
}
}
I used JSONObject from org.json library. I am also using Java 8 and its streams.
If you want to use gson you can use instead something like
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel;
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("stream").isJsonNull();
}
If you don't have Java 8 you can rewrite code reading text from URL to something like
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
or from what I see you can use your API.readJsonFromUrl instead of readFromUrl.
Ok so I got here is my sample JSON:
{
"messages":[
{
"receiver":"60:51:2c:93:6e:02",
"sender":"60:51:2c:93:6e:01",
"location":[
{
"longitude":"26.89478",
"latitude":"122.779953"
}
]
}
]
,"isSuccess":"true"
}
How can I retrieve every data inside it?
This is only what I got:
JSONObject jsonObject = parser.makeHttpRequest(someurl);
JSONArray messages = jsonObject.getJSONArray("messages");
If you are using the org.json lib
String json = "{\"messages\":[{\"receiver\":\"60:51:2c:93:6e:02\",\"sender\":\"60:51:2c:93:6e:01\",\"location\":[{\"longitude\":\"26.89478\",\"latitude\":\"122.779953\"}]}],\"isSuccess\":\"true\"}";
try {
JSONObject jsonObject = new JSONObject(json);
Boolean isSuccess = jsonObject.getBoolean("isSuccess");
JSONArray messages = jsonObject.getJSONArray("messages");
JSONObject firstElement = messages.getJSONObject(0);
String sender = firstElement.getString("sender");
JSONArray locationArray = firstElement.getJSONArray("location");
JSONObject firstLocation = locationArray.getJSONObject(0);
Double lng = firstLocation.getDouble("longitude");
Double lat = firstLocation.getDouble("latitude");
Log.d("Result", "isSuccess: " + String.valueOf(isSuccess)
+"\n Sender: " + String.valueOf(sender)
+"\n Latitude: " + String.valueOf(lat)
+"\n Longitude: " + String.valueOf(lng));
} catch (JSONException e) {
e.printStackTrace();
}
Or with less lines of code
Boolean isSuccess = jsonObject.getBoolean("isSuccess");
String sender = jsonObject.getJSONArray("messages").getJSONObject(0).getString("sender");
JSONObject firstLocation = jsonObject.getJSONArray("messages").getJSONObject(0).getJSONArray("location").getJSONObject(0);
Double lng = firstLocation.getDouble("longitude");
Double lat = firstLocation.getDouble("latitude");
What I also like with this library are the opt..() methods like optDouble() or optJSONObject() to avoid nested try/catch and define a default value if the key you are looking for doesn't exist.
I would suggest use JSCKSON APIs
refer below code
public static void main(String[] args) {
System.out.println("Hi");
String json = "{\"messages\":[{\"receiver\":\"60:51:2c:93:6e:02\",\"sender\":\"60:51:2c:93:6e:01\",\"location\":[{\"longitude\":\"26.89478\",\"latitude\":\"122.779953\"}]}],\"isSuccess\":\"true\"}";
ObjectMapper om = new ObjectMapper();
try {
JsonNode node = om.readTree(json);
System.out.println(node.get("messages").get(0).get("receiver"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to read this JSON file with java using json simple library.
My JSON file looks like this:
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
This is the java code I wrote to read this file:
package javaapplication1;
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 JavaApplication1 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\file.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
But I get the following exception:
Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)
Can somebody tell me what I am doing wrong? The whole file is a array and there are objects and another array (cars) in the whole array of the file. But i dont know how I can parse the whole array into a java array. I hope somebody can help me with a code line which I am missing in my code.
Thanks
The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.
As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) person.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
For reference, see "Example 1" on the json-simple decoding example page.
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
Add Jackson databind:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr2</version>
</dependency>
Create DTO class with related fields and read JSON file:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
Reading from JsonFile
public static ArrayList<Employee> readFromJsonFile(String fileName){
ArrayList<Employee> result = new ArrayList<Employee>();
try{
String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(text);
JSONArray arr = obj.getJSONArray("employees");
for(int i = 0; i < arr.length(); i++){
String name = arr.getJSONObject(i).getString("name");
short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
String position = arr.getJSONObject(i).getString("position");
byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company"));
if (position.compareToIgnoreCase("manager") == 0){
result.add(new Manager(name, salary, position, years_in_company));
}
else{
result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
}
}
}
catch(Exception ex){
System.out.println(ex.toString());
}
return result;
}
Use google-simple library.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Please find the sample code below:
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader("/resources/config.json"));//path to the JSON file.
String json = data.toJSONString();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
Use JSONObject for simple JSON like {"id":"1","name":"ankur"} and JSONArray for array of JSON like [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}].
Might be of help for someone else facing the same issue.You can load the file as string and then can convert the string to jsonobject to access the values.
import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
Gson can be used here:
public Object getObjectFromJsonFile(String jsonData, Class classObject) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(jsonData);
return gson.fromJson(object, classObject);
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Delete_01 {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException {
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
"delete_01.json"));
for (Object o : jsonArray) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String strCity = (String) person.get("city");
System.out.println("City::::" + strCity);
JSONArray arrays = (JSONArray) person.get("cars");
for (Object object : arrays) {
System.out.println("cars::::" + object);
}
String strJob = (String) person.get("job");
System.out.println("Job::::" + strJob);
System.out.println();
}
}
}
Following is the working solution to your problem statement as,
File file = new File("json-file.json");
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(file));
JSONArray jsonArray = new JSONArray(obj.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("city"));
System.out.println(jsonObject.get("job"));
jsonObject.getJSONArray("cars").forEach(System.out::println);
}
Hope this example helps too
I have done java coding in a similar way for the below json array example as follows :
following is the json data format : stored as "EMPJSONDATA.json"
[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},
{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},
{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}
{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]
public class Jsonminiproject {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
for (Object o : a)
{
JSONObject employee = (JSONObject) o;
Long no = (Long) employee.get("EMPNO");
System.out.println("Employee Number : " + no);
String st = (String) employee.get("EMP_NAME");
System.out.println("Employee Name : " + st);
String dob = (String) employee.get("DOB");
System.out.println("Employee DOB : " + dob);
String doj = (String) employee.get("DOJ");
System.out.println("Employee DOJ : " + doj);
String role = (String) employee.get("ROLE");
System.out.println("Employee Role : " + role);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.json;
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 ReadJSONFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));
JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) array.get(0);
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This issue occurs when you are importing the org. json library for JSONObject class. Instead you need to import org.json.simple library.
private static final JsonParser JSON_PARSER = new JsonParser();
private static final String FILE_PATH = "configuration/data.json";
private JsonObject readJsonDataFromFile() {
try {
File indexFile = new File(FILE_PATH);
String fileData = Files.toString(indexFile, Charsets.UTF_8);
return (JsonObject) JSON_PARSER.parse(fileData);
} catch (IOException | JsonParseException e) {
String error = String.format("Error while reading file %s", FILE_PATH);
log.error(error);
throw new RuntimeException(error, e);
}
}
public class JsonParser {
public static JSONObject parse(String file) {
InputStream is = JsonParser.class.getClassLoader().getResourceAsStream(file);
assert is != null;
return new JSONObject(new JSONTokener(is));
}
}
// Read Json
JSONObject deviceObj = new JSONObject(JsonParser.parse("Your Json filename").getJSONObject(deviceID).toString());
Perform logic to iterate
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonParserTest {
public static void main(String[] args) throws IOException {
String data = new String(Files.readAllBytes(Paths.get("C:/json.txt")));
JsonElement jsonElement = JsonParser.parseString(data);
JsonObject json = jsonElement.getAsJsonObject();
System.out.println(json.get("userId"));
System.out.println(json.get("id"));
System.out.println(json.get("title"));
System.out.println(json.get("completed"));
}
}
Use the below repositay from GSON.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Sample Json
{
"per_page": 3,
"total": 12,
"data": [{
"last_name": "Bluth",
"id": 1,
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"first_name": "George"
},
{
"last_name": "Weaver",
"id": 2,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
"first_name": "Janet"
},
{
"last_name": "Wong",
"id": 3,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
"first_name": "Emma"
}
],
"page": 1,
"total_pages": 4
}
First If statement will convert the single data from the body
Second if statement will differentiate the JsonArray object
public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
Object obj = responseJson;
for(String s : Jpath.split("/"))
if (s.isEmpty())
if(!(s.contains("[") || s.contains("]")))
obj = ((JSONObject) obj).get(s);
else
if(s.contains("[") || s.contains("]"))
obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));
return obj.toString();
}
}
Solution using Jackson library. Sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
your json file look like this
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
JSONObject jsonObject = (JSONObject)obj;
String name = (String)jsonObject.get("Name");
String course = (String)jsonObject.get("Course");
JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
System.out.println("Name: " + name);
System.out.println("Course: " + course);
System.out.println("Subjects:");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
the output is
Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML
took it from here
try {
Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
// JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) obj;
JSONObject orchestration = (JSONObject) jsonObject.get("orchestration");
JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
JSONObject schedule = (JSONObject) trigger.get("schedule");
JSONObject trade = (JSONObject) schedule.get("trade-query");
// loop array
JSONArray filter = (JSONArray) trade.get("filter");
for (Object o : filter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String operand = (String) person.get("operand");
System.out.println("City::::" + operand);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
JSONArray parameter = (JSONArray) trade.get("parameter");
for (Object o : parameter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
try {
//Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
// create object mapper instance
ObjectMapper mapper = new ObjectMapper();
// convert JSON string to Book object
Object obj = mapper.readValue(Paths.get("C:/Local Disk/file.json").toFile(), Object.class);
// print book
System.out.println(obj);
String jsonInString = new Gson().toJson(obj);
JSONObject mJSONObject = new JSONObject(jsonInString);
System.out.println("value::::" + mJSONObject);
JSONObject orchestration = (JSONObject) mJSONObject.get("orchestration");
JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
JSONObject schedule = (JSONObject) trigger.get("schedule");
JSONObject trade = (JSONObject) schedule.get("trade-query");
// loop array
JSONArray filter = (JSONArray) trade.get("filter");
for (Object o : filter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String operand = (String) person.get("operand");
System.out.println("City::::" + operand);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
JSONArray parameter = (JSONArray) trade.get("parameter");
for (Object o : parameter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use readAllBytes.
return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);