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
Related
I'm getting W/System.err: org.json.JSONException: Value when running this code to get the JSON. However, when I use:
[{"name":"Abhishek","password":"123","contact":"1111111111","country":"India"},{"name":"Rahul","password":"1s","contact":"1sdfsdf","country":"India"},{"name":"Abhishek","password":"aar","contact":"asdbsfg","country":"India"}]
(https://api.myjson.com/bins/j5f6b), a tester JSON URL, it gives me the output.
I have tried changing it to JSON Object in places but that isn't helping.
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("http://www.free-map.org.uk/fm/ws/bsvr.php?
bbox=-0.73,51.04,-0.71,51.06&way=highway&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection)
url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ;i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "name:" + JO.get("name") + "\n";
dataParsed = dataParsed + singleParsed +**"\n"** ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
twod.data.setText(this.dataParsed);
}
I expect a name output and am currently getting nothing but W/System.err: org.json.JSONException:
The problem seems to be with your parsing logic.
Check this:
JSONObject jsonObject = new JSONObject(data);
JSONArray JA = jsonObject.getJSONArray("features");
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
System.out.print(JO);
}
You have to create a JSONObject first, later extract the JSONArray from it.
Hello I'm trying to use this endpoint www.reddit.com/reddits.json to show some list on android and I'm getting this error, below is my code.
I have this asynctask class on my main activity class:
private class AsyncListLoader extends AsyncTask<String, Integer, JSONObject>{
private JSONParser jsonParser = new JSONParser();
private static final String REDEEM_URL = "http://www.reddit.com/reddits.json";
private HashMap<String, String> param = new HashMap<>();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject json = jsonParser.makeHttpRequest(REDEEM_URL, "GET", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
else {
Log.d("JSON result", "is null");
}
return null;
}
#Override
protected void onPostExecute(JSONObject s) {
try {
if(!s.has("kind")){
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
else {
JSONObject list = s.getJSONObject("data");
JSONArray childrens = list.getJSONArray("children");
for(int i = 0; i < childrens.length(); i++){
JSONObject o = childrens.getJSONObject(i).getJSONObject("data");
Feed f = new Feed(o.getString("icon_img"),o.getString("banner_img"),o.getString("display_name"));
MainActivity.this.adapter.add(f);
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
}
makehttpRequest when get:
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
I tested out another json endpoints on the web and they are working. I dont have any idea why is this happening.
EDIT:
No param is being used so the url is fine.
The json is valid, I checked this in differents websites.
I am trying to extract data from Json string which is obtained by a response using only Java code.
I am posting my Java code here.
OUTPUT:
Entering into while loop
[{"name":"Frank","food":"pizza","quantity":3}]
This is my Java code.
public void receive()
{
System.out.println("Entering into sendNote method");
try {
// make json string,
String json = "{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}";
// send as http get request
URL url1 = new URL("http://myurl/file.php?usersJSON="+userList);
URLConnection conn1= url1.openConnection();
//I am receiving exactly what I have sent....
BufferedReader rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
{
System.out.println("Entering into while loop");
System.out.println(line);// line contains the received json parameters
//I want to enter the recieved parameters into my database
//
//
//
//I need the solution right here....
}
rd.close();
}
catch (Exception e)
{
System.out.println("Error Occured while receiving");
e.printStackTrace();
}
}
Thank you !!!!!
#Ankur:
This is how I tried,
# Lahiru Prasanna, #ankur-singhal
Thanks a lot.!!
I think that you successfully got HttpResponse.here variable called response is HttpResponse.
// Could do something better with response.
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
content.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(builder.toString());
} catch (JSONException e) {
System.out.println("Error parsing data " + e.toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
System.out.println( "" + e.toString());
System.out.println("" + e.toString());
}
And important thing is never use Strings for json operations.
you can retrieve your data from jsonObject like this
String name = jsonObject.getString("name");
There are few ways to achive the same.
1.) Create a response pojo
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);
// then call getters on above.
2.) Get key/values
JSONObject json = (JSONObject)new JSONParser().parse(""name":"Frank","food":"pizza","quantity":3}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("food"));
3.) Converting Json to HashMap
public static void main(String[] args) {
try {
jsonToMap("{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}");
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : " + jObject);
System.out.println("map : " + map);
}
output
json : {"name":"Frank","food":"pizza","quantity":3}
map : {food=pizza, name=Frank, quantity=3}
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]
In my app, the class below receives a JSONArray and use its data to populate a ListView. I want the fields in this ListView to appear in an Alphabetical order. So I want to sort my JSONArray before using its data.
I've saw some topics suggesting to use GSON or Jackson, but I'm trying to do this in a simpler way. I don't understand well these libraries and did't find what I need in their tutorials.
An example of the JSON:
{"0":["1","Alimentos e Bebidas","Y"],"1":["6","Beleza e Cosm\u00e9ticos","Y"],"2":
["11","Cama, Mesa e Banho","Y"],"3":["3","CDs, DVDs e Games","Y"],"4":["2","Convites
e Cortesias","Y"],"5":["23","Cursos","Y"],"6":["8","Eletr\u00f4nicos","Y"],"7":
["16","Esporte e Lazer","Y"],"8":["14","Inform\u00e1tica e Acess\u00f3rios","Y"],
"9":["10","Limpeza","Y"],"10":["4","Livros","Y"],"11":["21","Livros no Sebo","Y"],
"12":["5","Outros","Y"],"13":["12","Roupas e Acess\u00f3rios","Y"]}
The class' method where I populate the list and wait for user:
public void proccess(){
listview = (ListView) findViewById(R.id.include3);
int qtdCategorias = json.length();
categorias = new String[qtdCategorias];
itens = new ArrayList<ItemListView>();
for (int i=0; i<qtdCategorias; i++){
c = json.optJSONArray(i);
String nomeCategoria = null;
try {
nomeCategoria = c.getString(1); //A consulta SQL do php retorna somente categorias habilitadas
} catch (JSONException e) {
Log.e("CategoriasShoppingActivity", e.toString());
e.printStackTrace();
}
categorias[i] = nomeCategoria;
//ItemListView item = new ItemListView(nomeCategoria);
//itens.add(item);
}
Arrays.sort(categorias);
for (int i=0; i<qtdCategorias; i++){
ItemListView item = new ItemListView(categorias[i]);
itens.add(item);
}
adapterListView = new AdapterListView(this, itens);
listview.setAdapter(adapterListView);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
c = json.optJSONArray(position);
String name = null;
String idt = null;
try {
name = c.getString(1);
idt = c.getString(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent in = new Intent(getApplicationContext(), ProdutosActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, idt);
startActivity(in);
}
});
}
[EDIT]
To request data from server, I use this JSONParser class ():
public class JSONParser{
static InputStream is = null;
static JSONArray jArr = null;
static JSONStringer jArrString = null;
static String json = "";
private static Context context;
private ProgressDialog loader;
// static HttpEntity httpEntity = null;
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// json = EntityUtils.toString(httpEntity);
// HttpEntity httpEntity2 = httpEntity;
json = EntityUtils.toString(httpEntity);
// is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("JSONParser", "IOException "+e.toString());
e.printStackTrace();
}
try {
char[] c = new char[json.length()];
json.getChars(0, json.length(), c, 0);
int i = 0;
while (c[i] == '\u00EF' || c[i] == '\u00BB' || c[i] == '\u00BF') { // remove
// utf-8
// BOM
i++;
}
json = json.substring(i);
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONObject json_data = new JSONObject(json);
JSONArray hashMap_names = json_data.names();
JSONArray hashMap_names2 = new JSONArray();
Map hashMap = new HashMap(json_data.length());
for (int i = 0; i != hashMap_names.length(); i++) {
hashMap.put(String.valueOf(i), json_data.get(String.valueOf(i)));
hashMap_names2.put(String.valueOf(i));
}
JSONObject hashMap_obj = new JSONObject(hashMap);
jArr = hashMap_obj.toJSONArray(hashMap_names2);
// jArr = new JSONArray(json);
Log.e("JSON Parser", "succesful parsing data " + jArr.toString());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
jArr = null;
}
// return JSON String
return jArr;
}
And here I receive the JSON in my class
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == 1){
if (resultCode == RESULT_OK){
try {
json = new JSONArray(data.getStringExtra(TAG_JSON));
Log.e("CategoriasShoppingActivity", "JSON: "+json);
} catch (JSONException e) {
e.printStackTrace();
}
proccess();
}else{ // resultCode == RESULT_CANCELED
Log.d("CategoriasJogarActivity", "AsyncTaskActicity retornou RESULT_CANCELED");
finish();
}
}
}
If you have access to server-side code, it will be easier to sort the list there. If not, your only way to do so, is to parse it to ArrayList and simply sort it using any known algorithm.
Why don't you sort it before serializing ? Use Comparator interface and sort it using Collections.sort. Pass the comparator as as the parameter when sorting