Array and Object JSON from URL Parsing - java

I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}

JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.

please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.

Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}

Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}

you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"

Related

Retrieve data to ListView from API in android

I need to retrieve data to listview from this link http://www.autotrack.rs/android_juzna_backa/get_voznja.php?. I need to send key, with value-POST method, to get something like this: http://www.autotrack.rs/android_juzna_backa/get_voznja.php?voznja_id=42. My code is bellow: Thanks. ERROR Value null at data of type org.json.JSONObject$1 cannot be converted to JSONArray
public class fetchData extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
super.onPreExecute();
swipeRefresh.setRefreshing(true);
}
#Override
protected String doInBackground(String... params) {
arrayList.clear();
String result = null;
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("voznja_id", "42")
.build();
Request request = new Request.Builder()
.url("http://www.autotrack.rs/android_juzna_backa/get_voznja.php")
.method("POST", body)
.build();
try {
response = client.newCall(request).execute();
// System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
public void onPostExecute(String rezultat) {
try {
rezultat = response.body().string();
}catch (Exception m)
{
m.printStackTrace();
}
Intent intent;
Gson gson = new Gson();
Type type = new TypeToken<Voznja>() {
}.getType();
Voznja voznja = gson.fromJson(rezultat, type);
Intent im = new Intent(getApplicationContext(), Unos.class);
im.putExtra("voznja", voznja);
// startActivity(im);
swipeRefresh.setRefreshing(false);
try {
JSONObject object = new JSONObject(rezultat);
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
VoznjaAdapter adapter = new VoznjaAdapter(ListaVoznji.this, arrayList);
listView.setAdapter(adapter);
Your api response is JSONObject.
{"data":{"id":"42","vozilo_id":"777777003561","vozac_id":"2","pocetna_kilometraza":"50000","pocetno_vreme":"2020-12-25 07:15:00","projekat":null,"razlog":"Sastanak","zavrsna_kilometraza":"50150","zavrsno_vreme":"2020-12-25 10:45:00","moto_sati":"3","insert_time":"2021-01-08 10:47:33.683885","id_projekat_jb":"330"}}
So you should use JSONObject instead JSONArray
try {
JSONObject object = new JSONObject(rezultat);
JSONObject jsonObject = object.getJSONObject("data");
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}

How to get the values of a key of a json file

How can i get the values of a json key in Java here is my code
private void getWebApiData() {
String WebDataUrl = "myjsonfileurl";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("A");
String name = sourceObject.optString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My json file
{
"books": [
{
"A": [
{
"Amazonite": {
"name": "Amazonite",
"image": "www.google.com"
},
"Amethyst": {
"name": "Amethyst",
"image": "www.google.com"
}
}
],
"B": [
{
"Beryl": {
"name": "Beryl",
"image": "www.google.com"
},
"BloodStone": {
"name": "Bloodstone",
"image": "www.google.com"
}
}
]
}
]
}
What i would like is how to get the values of data under the Alphabet A that is Amazonite and Amethyst and the value of data under Alphabet B but the could i have just give me empty text field nothing no data is being populated.
I have tried with this code but the values retures "null"
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
String name = String.valueOf(articleObject.optJSONObject("A"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am not sure what you really want, but if you just want to get "Amazonite and Amethyst" as you responded under OP, you can try this:
Code snippet
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONArray jsonArrayA = articleObject.getJSONArray("A");
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
System.out.println(obj.names());
obj.names().forEach(e -> {
System.out.println(obj.getJSONObject(e.toString()).get("name"));
});
}
}
Console output
["Amazonite","Amethyst"]
Amazonite
Amethyst
Update
I am not sure which name you want to retrieve because both Amazonite and Amethyst appear two times in JSON array A, so I provide two ways to show them as follows:
List<String> names = new ArrayList<>();
List<String> innerNames = new ArrayList<>();
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
JSONArray keys = obj.names();
for (int k = 0; k < keys.length(); k++) {
String name = keys.getString(k);
String innerName = obj.getJSONObject(keys.optString(k)).getString("name");
System.out.printf("name: %s, inner name: %s\n", name, innerName);
names.add(name);
innerNames.add(innerName);
}
}
System.out.println(names.toString());
System.out.println(innerNames.toString());
Console output
name: Amazonite, inner name: Amazonite
name: Amethyst, inner name: Amethyst
[Amazonite, Amethyst]
[Amazonite, Amethyst]

Proper way to format a JSON object and send to server via volley

I'm trying to use the Safe Browsing API from google to check if a web link is black listed, just need to send a request within a JSON object to:
POST https://safebrowsing.googleapis.com/v4/threatMatches:find?key=API_KEY HTTP/1.1
Content-Type: application/json
And the JSON object should be like:
{
"client": {
"clientId": "mycompanyname",
"clientVersion": "1.1"
},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["WINDOWS"],
"threatEntryTypes": ["URL"],
"threatEntries": [
{"url": "http://www.urltocheck1.org/"},
{"url": "http://www.urltocheck2.org/"},
{"url": "http://www.urltocheck3.com/"}
]
}
}
But already I don't know if I am formatting my JSON object properly, or my code is correct, see below:
public class SB {
private ArrayList<String> url; //URL's a analizar
private String key; //API key
private RequestQueue queue;
private Context context;
private ArrayList<SBthreat> AnalyzedUrl; //analysis final
private boolean Interrupted = false;
private boolean CallFail = false;
public SB(Context context, ArrayList<String> url, String key){
this.url = url;
this.key = key;
this.context = context;
queue = Volley.newRequestQueue(context);
AnalyzedUrl = new ArrayList<>();
}
public void Request(){
final StringBuilder api = new StringBuilder("https://safebrowsing.googleapis.com/v4/threatMatches:find?key=");
JSONObject requestBody = new JSONObject();
//JSON body
try {
JSONObject client = new JSONObject();
client.put("clientId", "NetworkSentinel");
client.put("clientVersion", "1.2");
JSONObject threatEntries = new JSONObject();
for(int i = 0; i < this.url.size(); i++){
threatEntries.put("url", this.url.get(i)); //-----> the url can be too many
}
JSONObject threatInfo = new JSONObject();
threatInfo.put("threatTypes", "[\"MALWARE\", \"SOCIAL_ENGINEERING\"]");
threatInfo.put("platformTypes", "[\"WINDOWS\"]");
threatInfo.put("threatEntryTypes", "[\"URL\"]");
threatInfo.put("threatEntries", threatEntries);
JSONObject jsonBody = new JSONObject();
jsonBody.put("client", client);
jsonBody.put("threatInfo", threatInfo);
requestBody.put("", jsonBody);
}catch (JSONException e) {
e.printStackTrace();
}
api.append(key).append(" HTTP/1.1");
Log.i("SB", api.toString().replace(key, "XXXXXXXXXXXXX"));
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, api.toString(), requestBody, future, future){
#Override
public HashMap<String, String> getHeaders() {
HashMap<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
queue.add(request);
try {
JSONObject response = future.get();
if(response.length() != 0) {
Log.i("SB", "-----------------------------------------------------------------------");
Log.i("response", response.toString());
Interrupted = false;
CallFail = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
Interrupted = true;
} catch (ExecutionException e) {
e.printStackTrace();
CallFail = true;
}
}
public ArrayList<SBthreat> GetAnalysis(){
return AnalyzedUrl;
}
public boolean isInterrupted(){
return Interrupted;
}
public boolean isCallFail(){
return CallFail;
}
}
Is the code threatInfo.put("threatTypes", "[\"MALWARE\", \"SOCIAL_ENGINEERING\"]"); well written? Or is there is a better way to put data in square brackets?
When I run my code always get the error com.android.volley.ClientError and connections errors, what I'm doing wrong?
You should use JSONArray and don't use [ ] to place manually. Please refer below:
JSONObject client = new JSONObject();
client.put("clientId", "mycompanyname");
client.put("clientVersion", "1.1");
JSONObject threatInfo = new JSONObject();
JSONArray threatTypes = new JSONArray();
threatTypes.put("MALWARE");
threatTypes.put("SOCIAL_ENGINEERING");
JSONArray platformTypes = new JSONArray();
threatTypes.put("WINDOWS");
JSONArray threatEntryTypes = new JSONArray();
threatTypes.put("URL");
JSONArray threatEntries = new JSONArray();
for(int i = 0; i < this.url.size(); i++){
JSONObject threatEntry = new JSONObject();
threatEntry.put("url", this.url.get(i)); //-----> the url can be too many
threatEntries.put(threatEntry);
}
threatInfo.put("threatTypes", threatTypes);
threatInfo.put("platformTypes", platformTypes);
threatInfo.put("threatEntryTypes", threatEntryTypes);
threatInfo.put("threatEntries", threatEntries);

how to parse a json file when starts with

I want to parse the following JSON file but is starting with [ indicating to me that is an array, and then continues with { objects, my current parser is returning a JSON object.
My question is: how to modify the parser to parse this file? So that the parser will serve me for other JSON files, starting with objects or arrangements.
JSON FILE:
[{"codigo":1,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"1 lomo completo y 1 cerveza de lt","precio":100.0},{"codigo":2,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"2 lomo completo y 2 cerveza de lt","precio":190.0},{"codigo":3,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"3 lomo completo y 3 cerveza de lt","precio":280.0},{"codigo":4,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"4 lomo completo y 4 cerveza de lt","precio":370.0}]
JSON PARSER
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Try to parser JSON FILE
public class OfertaService extends Service {
private static final String URL = "http://192.168.0.13:8080/ofertas/listado";
private static final String TAG_CODIGO = "codigo";
private static final String TAG_CONTENIDO = "contenido";
private static final String TAG_DESCRIPCION = "descripcion";
private static final String TAG_PRECIO = "precio";
private static final String TAG_CODIGO_PRODUCTO = "codigo";
private static final String TAG_DESCRIPCION_PRODUCTO = "descripcion";
#SuppressWarnings("rawtypes")
private List listaOfertas = new ArrayList();
public List getListaOfertas() {
return listaOfertas;
}
public void setListaOfertas(List listaOfertas) {
this.listaOfertas = listaOfertas;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("unchecked")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
new DoInBack().execute();
} catch (Exception e) {
System.out.println("error en proceso de segundo plano DoInBack");
}
return 0;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private class DoInBack extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray ofertasArray = null;
JSONArray productos = null;
JSONObject json = jParser.getJSONFromUrl(URL);
try {
String codigo = json.getString(TAG_CODIGO);
for (int i = 0; i < ofertasArray.length(); i++) {
JSONObject of;
of = ofertasArray.getJSONObject(i);
String id = of.getString(TAG_CODIGO);
// productos = json.getJSONArray(0);
List listaProductos = new ArrayList();
for (int j = 0; j < productos.length(); j++) {
JSONObject pro = productos.getJSONObject(j);
String idProducto = pro.getString(TAG_CODIGO_PRODUCTO);
String descProducto = pro
.getString(TAG_DESCRIPCION_PRODUCTO);
Hashtable<String, String> producto = new Hashtable<String, String>();
producto.put(TAG_CODIGO_PRODUCTO, idProducto);
producto.put(TAG_DESCRIPCION_PRODUCTO, descProducto);
listaProductos.add(producto);
}
String descripcionOferta = of.getString(TAG_DESCRIPCION);
String precio = of.getString("precio");
Hashtable ht = new Hashtable();
ht.put(TAG_CODIGO, id);
ht.put(TAG_CONTENIDO, listaProductos);
ht.put(TAG_DESCRIPCION, descripcionOferta);
ht.put(TAG_PRECIO, precio);
listaOfertas.add(ht);
}
System.out.println("parseo finalizado");
} catch (Exception e) {
}
return null;
}
}
I want to parse the following JSON file but is starting with [
indicating to me that is an array
When json string starting with [ means string is JSONArray
how to modify the parser to parse this file?
1. Convert json String to JSONArray instead of JSONObject:
JSONArray jsonArray = new JSONArray(json);
2. Change return type of getJSONFromUrl method to JSONArray from JSONObject
3. In doInBackground get response from getJSONFromUrl method in JSONArray:
JSONArray jsonArray = jParser.getJSONFromUrl(URL);

I can't loop through JSON Array for next Array

I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}

Categories