Accessing JSON property name using java - java

I'm working on a way to parse JSON files and collect their contents for use elsewhere. I currently have a working example that is as follows:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testJSONParser {
public static void main(String[] args) throws Exception {
List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
try {
String line = br.readLine();
while (line != null) {
JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);
Map<String, String> currentLineMap = new HashMap<String, String>();
currentLineMap.put("country", jsonObject.get("country").toString());
currentLineMap.put("size", jsonObject.get("size").toString());
currentLineMap.put("capital", jsonObject.get("capital").toString());
jsonArray.add(currentLineMap);
line = br.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
};
}
}
}
I'm using the json simple library for parsing the passed in JSON strings.
Here's a sample string from the parsed file.
{"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"}
What my question is about is how to take this code, and have the put method be able to assign to the corresponding Map dynamically. This is what I currently have:
for (int i = 0; i < jsonObject.size(); i++) {
currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}
The ??? part is where I'm stumped. Getting the values of the current JSON line is easy enough. But how to get the property values (highlighted in bold in the JSON string sample) eludes me. Is there a method that I can call on this object that I'm not familiar with? A different and better way to itenerate through this? Or am I doing this completely assbackwards right from the get go?

In the JSON.org reference implementation, you could do:
for (String key : JSONObject.getNames(jsonObject))
{
map.put(key, jsonObject.get(key));
}
In JSON simple, you would do:
for (Object keyObject : jsonObject.keySet())
{
String key = (String)keyObject;
map.put(key, (String)jsonObject.get(key));
}
This should do the trick.

Related

read JSON from url on JavaFX controller does not update when JSON updated

I try to create java program that read JSON from this url, the url contain JSON array that updated every 20 seconds here is my java program that listen to the url and print the last JSON object from the JSON file:
ListenTojson.java
package com.company;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
class ListenToJson implements Runnable {
public void run() {
long tenSeconds = 10*1000L;
while(true) {
try {
JSONArray json = readJsonFromUrl("http://frozen-brook-16337.herokuapp.com/history.json");
JSONObject jo=json.getJSONObject(json.length()-1);
System.out.println(jo.get("data"));
Thread.sleep(tenSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONArray jsonArray = new JSONArray(jsonText);
return jsonArray;
} finally {
is.close();
}
}
}
Main.java
package com.company;
public class Main {
public static void main(String[] args){
(new Thread(new ListenToJson())).start();
}
}
The code run as I expected. The JSON file contains coordinate that keep updated every 10 seconds. I need to create map application that read the coordinate from the JSON and then show it on the map as marker, I use JavaFx library to create the map application, when I add the code above (ListenToJson.java) the program behave differently when I use JavaFX library it does not read the latest JSON file.
here is the code
public class Controller{
//some code
(new Thread(new ListenToJson())).start();
//some code
}
Controller.java
The full class that I try to update the UI using the ListenToJson() function is here https://github.com/kikirizki/mapapp/blob/master/src/main/java/com/delameta/vesselmap/Controller.java the line 526, thanks
whats wrong with my code, why the ListenToJson() function read the outdated JSON file ?
I found the solution myself, the problem is the mapjfx library (I use in the code) use cache to cache the map tile and then it cause to cache the JSON file too. The solution is simply disable the cache mechanism, just diable it at line 350, change
offlineCache.setActive(true);
to be
offlineCache.setActive(false);

How do I read from JSON File in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I've read some other questions about this, but they did not seem to help me.
As the title says, I want to know how to read from .json files using Java.
Eg. I want my program to read a boolean value. (That is what I want it to.)
I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed.
What I've found so far (That did not work):
String str = "Name";
JSONObject obj = new JSONObject();
String n = (String) obj.get("Name");
if (!n.equals("true")) {
} else
if (n.equals("true")) {
ButtonsShow = true;
} else if (n.equals("false")) {
ButtonsShow = false;
}
Click to view the .Json file
you try it:
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 JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

error: non-static method get(Object) cannot be referenced from a static context

The code below shows:
JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context
JSONArray cars = (JSONArray) JSONObject.get("cars");
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 {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt"));
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) JSONObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Anyone has any idea why this is the case?
(by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.)
Project: Code from StackOverflow page How to read json file into java with simple JSON library
Code Author: https://stackoverflow.com/users/1212960/greg-kopff
Check this line
JSONArray cars = (JSONArray) JSONObject.get("cars");
change it with
JSONArray cars = (JSONArray) person.get("cars");
Issue was since you are calling the get method directly on the class.

Not able to get particular value from java object using yaml method

I am using yamlbeans to get data from yaml file. i am getting following response
{x1=[{y1=z1}, {y2=z2}], x2=[{y1 =z1}, {y2=z2]}
Now i want to get data y1 of x1 but i am not able to do this. I am using following code for read operation
package com.mobileapp;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.yamlbeans.YamlReader;
public class ReadDataWithYaml {
public static void main(String[] args) {
try {
YamlReader reader = new YamlReader(new FileReader("C:\\Users\\5521\\Desktop\\test.yml"));
Object object = reader.read();
System.out.println(object);
Map<String, ArrayList<String>> map = (Map<String, ArrayList<String>>) object;
System.out.println(map.get("x1"));
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Yaml yaml1 = new Yaml();
InputStream inputStream1 = Main.class.getClassLoader().getResourceAsStream("YourYaml.yaml");
Map< String, Object> result = (Map< String, Object>) yaml1.load(inputStream1);
for (Object name : result.keySet()) {
System.out.println(result.get(name).toString());
}
String x= result.get("userInput").toString();
System .out.println(""+x);

Parsing the web page response as Json, in Java

I have a java code:
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
Which is opening the connection and printing the contents of it. The contents are indeed Json. The output is something like:
{
"merchantId": "guest",
"txnId": "guest-1349269250-001",
}
I wish to parse this in json simple jar. I changed the code loop like this:
JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
obj.put("Result",inputLine);
But that doesn't seem to be working. The output I'm getting is:
{"Result":"}"}
You should use the JSONParser#Parse() method or the JSONValue#parse() method :
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());
Object json = JSONValue.parse(in);
Are you sure you're following the documentation on how to parse a JSON string?
By the looks of it you have to obtain the entire string and call a JSONParse#parse() on it, but your code is filling up a HashMap (JSONObject's parent class) with each of the lines of the JSON. In fact it stores just the last line because you're calling put() with the same "Result" key on every iteration.
You should read whole contents to String variable first and parse it to json. Be careful of ""(double quote). Java uses \" for double quote. Like.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample3 {
public static void main(String args[]) {
JSONParser parser = new JSONParser();
//String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";
//intilize an InputStream
InputStream is = new ByteArrayInputStream("file content".getBytes());
//read it with BufferedReader and create string
BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
// parse string
try {
JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());
String merchantId = (String) jsonObject.get("merchantId");
System.out.println(merchantId);
String txnId = (String) jsonObject.get("txnId");
System.out.println(txnId);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
try this link its really helpful if you are going to be logging in or staff like that
Java Json simple
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
* {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
* "dataset":
* [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
* {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

Categories