Parsing all JSONObject in JSON file using java - java

My purpose is to parse twitter data which is described in JSON file. I created a void for parsing JSON which function perfectly, but it show me only one JSONObject while my `
public void parsingJson( String d) throws Exception
{
BufferedReader br = null;
//JSONObject rootObejct=null;
JSONObject js=new JSONObject();
try {
String sCurrentLine;
InputStream inputStream = new FileInputStream("E://inputdata.json") ;
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
br = new BufferedReader(inputStreamReader);
while ((sCurrentLine = br.readLine())!= null) {
JSONObject rootObejct=new JSONObject(sCurrentLine);
for(#SuppressWarnings("unchecked")
Iterator<String> iter = rootObejct.keys();iter.hasNext();) {
String key = iter.next();
try {
if (key.startsWith(d)){
System.out.println("******key*********"+key);
Object value = rootObejct.get(key);
System.out.println("keys vlaue "+value.toString());
}
} catch (JSONException e) {
// Something went wrong!
}
}
}
`

Here's a simple code to read a JSON file
public void readJSONFile(String filePath) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filePath));
JSONObject jsonObject = (JSONObject) obj;
//if your value is an array
JSONArray arr = (JSONArray) jsonObject.get("array");
//if your value is string
String str = (String) jsonObject.get("status");
} catch (Exception e) {
e.printStackTrace();
}
}
JSON file used as test case is
{
"status": "OK",
"array": [ "Hello" ]
}
If it doesn't help, please let me know.

Related

Sorting the json file

Hi I am working on a project it will show USD EUR TRY Bitcoin Gold values i have api for all of this values in json i want to sort them out my json link is this https://canlidoviz.com/doviz-kurlari.jsonld
I am parsing the json with this class
public class ClassJSONParser {
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
public ClassJSONParser(){
}
public JSONObject getJSONFromURL(String url) {
try {
URL urlObject = new java.net.URL(url);
HttpURLConnection conn=(HttpURLConnection) urlObject.openConnection();
conn.setRequestMethod("GET");
is = new BufferedInputStream(conn.getInputStream());
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
String tmp = line + "/n";
sb.append(tmp);
}
is.close();
json=sb.toString();
}catch (Exception e){
Log.i("Buffer Error","Error Converting Result"+e.toString());
}
try {
if(json !=null){
jObj=new JSONObject(json);
}else{
jObj=null;
}
}catch (JSONException e){
}
return jObj;
}
}
and getting a string like this
ClassJSONParser jParser = new ClassJSONParser();
String url = "https://canlidoviz.com/doviz-kurlari.jsonld";
jsonO= jParser.getJSONFromURL(url);
Log.d("***",jsonO.toString());
what method should i use how can i do can you give me guidance

How can I convert an ArrayList to JSON Object to be able to iterate through it in Java?

I am trying to loop through a json object I pulled through the web but I can't seem to convert it from a string to a jsonarray or jsonobject. I want to be able to use a for loop to iterate through it and then conditionally output names based on some values.
This is a simple java program to demonstrate pulling json data from a web api and then looping through it.
Here's the code:
public static List<String> getUsernames(int threshold) throws IOException {
List<String> usernames = new ArrayList<>();
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("url to json api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//Request method
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
System.out.println(status);
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
usernames.add(line);
}
// String json = new Gson().toJson(usernames);
//
// JSONArray jsonarray = new JSONArray(json);
// System.out.println(json);
Gson gson = new Gson();
reader.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return usernames;
}
List<String> usernames = new ArrayList<>();
usernames.add("Hibernate");
usernames.add("spring");
JSONArray jsonStr = new JSONArray().put(usernames);
for (Object values: jsonStr) {
System.out.println(values);
}

How to convert a String to a JsonObject

I am using a HttpURLConnection to get Json from a web into a string.
And i'm storing web string into BufferedReader and after that storing it in a new String.
And string is here:-
{"coord":{"lon":72.85,"lat":19.01},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":302.131,"pressure":1024.24,"humidity":84,"temp_min":302.131,"temp_max":302.131,"sea_level":1024.75,"grnd_level":1024.24},"wind":{"speed":4.77,"deg":302.001},"clouds":{"all":12},"dt":1459677392,"sys":{"message":0.0102,"country":"IN","sunrise":1459645229,"sunset":1459689786},"id":1275339,"name":"Mumbai","cod":200}
How can i convert it into JsonObject.
I've also seen this answer (How to convert String to JsonObject) but it's not working.
Here is code:-
BufferedReader br= new BufferedReader(new InputStreamReader(conn.getInputStream()));
String localoutput;
while ((localoutput = br.readLine()) != null)
{
output=localoutput+output;
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e);
}
JsonReader jsonReader = Json.createReader(new StringReader(output));
JsonObject object = jsonReader.readObject();
jsonReader.close();
try {
String cityname = object.getString("name");
System.out.println(cityname);
}
catch (Exception e)
{
e.printStackTrace();
}
Here output is the String which I've mentioned it earlier.
I'm not getting the Output Cityname in my console.
Use this library. It provides very simple API, to convert a String to json object simply do the following:
try {
JSONObject object = new JSONObject(yourJsonString);
} catch (Exception e){
e.printStackTrace();
}

JSON with Setter/Getter

In Selenium, I'm using the JSON file to fetch the data and passing them into Getter methods of certain private variables, but it is throwing an error org.openqa.selenium.WebDriverException: unknown error: keys should be a string
Below are the lines of code :
public class ABC {
private String systemName;
JSONObject jsonObj = null;
public ABC() {
File filePath = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObj = jsonObject;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public String getSystemName() {
return (String) jsonObj.get("SystemName");
}
}
public class DEF {
ABC abc = new ABC();
String testString = abc.getSystemName();
}
Here the value of testString is set to null.
(All the required packages are imported)

What am I doing wrong in this parsing?

I am currently parsing through reddit.com/.json with Google Gson and having some trouble. After doing some research I found a way to parse through json with Gson without making a lot of classes. I am using this method. Here is my code so far:
import java.io.*;
import java.net.*;
import com.google.gson.*;
public class Subreddits {
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null){
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();//String of json
System.out.println(json);
//I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("data").getAsJsonObject("children").getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
System.out.println(subreddit);
}
}
You are trying to get the element "children" as a JsonObject, but it is a JsonArray because it is surrounded by [ ]...
Try something like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
//Here is the change
JsonObject locObj = rootObj
.getAsJsonObject("data")
.getAsJsonArray("children")
.get(0)
.getAsJsonObject()
.getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
Note: I assume that you only want to get the data of the first element of the "children" array, since it seems that it is what you want looking at your code and mainly looking at this other question of yours.
The children object returns an Array that you must iterate.
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null) {
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();// String of json
System.out.println(json);
// I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray locObj = rootObj.getAsJsonObject("data").getAsJsonArray("children");
/* Iterating children object */
Iterator<JsonElement> iterator = locObj.iterator();
while(iterator.hasNext()){
JsonElement element = iterator.next();
JsonElement subreddit = element.getAsJsonObject().getAsJsonObject("data").get("subreddit");
System.out.println(subreddit.getAsString());
}
}
You don't need to create try..catch block for every expression that can throw an exception.
JsonParser.parse() method accepts Reader (e.g. InpustStreamReader) instance so you don't have to read JSON on your own.
root[data][children] is an array of objects so you'll have to iterate over them in order to gain access to individual objects.
I believe you want to read all [subredit]s into some sort of collection, Set I pressume?
public static void main(String[] args) {
try {
Set<String> subreddits = new HashSet<>();
URL url = new URL("http://www.reddit.com/.json");
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(new InputStreamReader(url.openConnection().getInputStream())).getAsJsonObject();
JsonArray children = root.getAsJsonObject("data").getAsJsonArray("children");
for (int i = 0; i < children.size(); i++) {
String subreddit = children.get(i).getAsJsonObject().getAsJsonObject("data").get("subreddit").getAsString();
subreddits.add(subreddit);
}
System.out.println(subreddits);
} catch (IOException e) {
e.printStackTrace();
}
}
This code returns:
[IAmA, worldnews, technology, news, todayilearned, gaming, AskReddit, movies, videos, funny, bestof, science, WTF, politics, aww, pics, atheism, Music, AdviceAnimals]

Categories