What am I doing wrong in this parsing? - java

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]

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 to return a json string in php for using it in java

I want wrote an API in php for using it in my android app. In the php side I do this for return info in an array
echo json_encode($array)
result of this code is like this, see online result in this link:
{"value":[{"id":"1","name":"kufta","meal":"1","photo_id":"","explanation":"xoshmazas","foodtime":"0000-00-0000:00:00"},{"id":"2","name":"\r\nAsh","meal":"2","photo_id":"","explanation":"sdfdsfsdfdsfdsfsdf","foodtime":"2017-06-26 14:00:00"},{"id":"3","name":"kabab","meal":"3","photo_id":"","explanation":"kabab kheili khoshmaze ast","foodtime":"2017-06-29 00:00:00"}]}
but in java side when I load this, app crash but when I use this json string in this site. Android app works fine
my java code for reading the url content
public class WebService {
private String connectToServer(String address, String requestMethod) {
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(requestMethod);
return inputStreamToString(httpURLConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String inputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = reader.readLine()) != null) {
stringBuilder.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
line 23 : public List<FoodModel> getFoods(){ <-----------Error is here
String response = connectToServer("http://mtg1376.gigfa.com/api/food?day=All","GET");
if(response != null){
List<FoodModel> foodList = new ArrayList<😠);
try{
JSONObject mainObject = new JSONObject(response);
JSONArray foodArray = mainObject.getJSONArray("value");
for(int i = 0 ; i< foodArray.length();i++){
JSONObject foodObject = foodArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.id = foodObject.getString("id");
foodModel.name = foodObject.getString("name");
foodModel.meal = foodObject.getString("meal");
foodModel.photo_id = foodObject.getString("photo_id");
foodModel.explanation = foodObject.getString("explanation");
foodModel.foodtime=foodObject.getString("foodtime");
foodList.add(foodModel);
}
return foodList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null; }
}
java error log : https://ibb.co/hQneXk
whats the problem?

Parsing all JSONObject in JSON file using 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.

Empty JSON response when trying to parse JSONObject with one JSONArray

I got code that gets JSONArrays, but however when I try to get JSONObject that contains only one JSONArray it gives me empty JSONArray.
For example if I need to get data from this JSONObject:
{"events":[{"start":1357714800,"end":1357736400,"name":"Example1","description":""}]}
I get {"events":[]} as JSONObject, [] meaning that it doesn't contain any JSONArrays. Also length of JSONObject is in this case 0. But it doesn't throw any kind of Exceptions.
but if JSONObject contains multiple JSONArrays like this:
{"events":[{"start":1357714800,"end":1357736400,"name":"Example1","description":""},{"start":1357714600,"end":1357736500,"name":"Example2","description":""},{"start":1357514800,"end":1357536400,"name":"Example3","description":""}]}
then my code works perfect.
Here is the code I use to parse JSON:
private void getObjects(String url) throws JSONException, Exception {
JSONObject jsonObject = new JSONObject(new NetTask().execute(url).get());
JSONArray job1 = jsonObject.getJSONArray("events");
System.out.println(jsonObject.toString());
System.out.println("JOB1 LENGTH: "+job1.length());
for (int i = 0; i < job1.length(); i++) {
JSONObject jsonEvent = job1.getJSONObject(i);
int start = jsonEvent.getInt("start");
int end = jsonEvent.getInt("end");
String name = jsonEvent.getString("name");
String description = jsonEvent.getString("description");
}
}
public class NetTask extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params)
{
String jsonText = "";
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
jsonText = buffer.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return jsonText;
}
}
is there something wrong that I am missing or is this normal behaviour?
I tried your given code (though I just made the AsyncTask just return the single-array string, and had to replace the opptunti.getString() stuff with jsonEvent.getString()). It worked fine, aside from the fact that you're probably blocking the UI thread to wait for the server response.
My guess is the problem is that you are hitting the wrong URL, that the parameters are wrong or something like that.

Looping and converting JSON Object to Array

I'm new to Java and programming for Android and I've seen a lot of tutorials but I am kinda clueless atm on how to loop through a JSONObject and set it to my class.
Example of JSON data:
http://sickbeard.com/api/#history
Class I made:
public Episode(JSONObject obj) {
try {
this.id = Integer.parseInt(obj.getString("episode").toString());
this.tvId = Integer.parseInt(obj.getString("tvdbid").toString());
this.resource = obj.getString("resource").toString();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
I came as far as this...
ArrayList<Episode> episodeList = new ArrayList<Episode>();
JSONObject data = new JSONObject();
for(int i = 0; i < 2; i++) {
try {
data = response.getJSONObject("data");
episodeList.add(new Episode(data));
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
// for each entry create new episode :)
} else {
return null;
}
Found it :)
try {
response = new JSONObject(con.query("history", parameters));
JSONArray data = response.getJSONArray("data");
for(int i = 0; i < data.length(); i++) {
try {
episodeList.add(new Episode((JSONObject) data.get(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// is = entity.getContent();
ArrayList<String> myList = new ArrayList<String>();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
myList.add(json_data.getString("id"));
Log.i("log_tag","id: " + json_data.getString("id"));
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return myList;
// then u can recieve this myList :
ArrayList<String> get_data_id = postData();
// get_data_id = myList
get_data_id.get(0) - it is first element,
get_data_id.get(1) - it is second element
....
EXAMPLE
json data is : [{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"}]
{in loop} myList.add(json_data.getString("id"));
get_data_id.get(0) = 1
get_data_id.get(1) = 2
get_data_id.get(2) = 3
..........
:)
Good Luck

Categories