Iterating through JSON data converted from multidimensional array - android

THIS WORKS FINE
I have this code block to read a json data that I am getting from FetchData.php file; My code looks like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/mydummyproject/FetchData.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("name");
String verion = object.getString("version");
textView.setText(name + " - " + verion);
}
catch (JSONException e) {
e.printStackTrace();
}
Data from my PHP File FetchData.php
{"name":"John Doe","version":"Android 4.4"}
PROBLEM
I also have another type of data coming from FetchDataTwo.php
[{"name":"John Doe","version":"Android 4.4"}, {"name":"Seliana Gomez","version":"Android 4.1"}, {"name":"Nerdy Trumph","version":"Android 4.4"}]
Now the above one is also a json data that I have got by doing json_encode($multidimensional_array) in PHP file.
ISSUE
How to loop over this multidimensional encoded array from json. So that I can iterate over like this (json data by json data):
[NOTE: Below is the data that I need to fetch, I don't want to arrange in the displayed fashion. That's just for clarity and example]
Name | Version
John Doe | Android 4.4
Seliana Gomez | Android 4.1
Nerdy Trumph | Android 4.4
Basically as a logic something like this:
//Loop over each json object
for data in JSONObject:
// Print name and version
textView.setText(data.name + " - " + data.version)

It looks like all you have to do is iterate over the JSONArray
try {
JSONArray array = new JSONArray(inputString);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.optJSONObject(i);
// Json Object handling...
}
} catch (JSONException e) {
// handle
}
But really, using Gson should be way easier. It can parse the contents for you into a simple java object. You can annotate a POJO class with the field names and Gson does all the work.
public class NameVersionPair {
private interface Json {
String NAME = "name";
String VERSION = "version";
}
#SerializedName(Json.NAME)
private String mName;
#SerializedName(Json.VERSION)
private String mVersion;
public String getName() {
return mName;
}
public String getVersion() {
return mVersion;
}
}
Then use a Gson instance to parse your string automatically
Gson gson = new Gson();
NameVersionPair[] result = gson.fromJson(inputString, NameVersionPair[].class);

Related

JSON Parsing of single array and name of Array

I need to show response on Sign Up, below is my JSON Response.
I should show password is too short(minimum is 5 characters) into one string
{ errors: { password: [ "is too short (minimum is 5 characters)" ] } }
And also I need to parse the response from the following JSON data
as Signature has already been taken
{ errors: { signature: [ "has already been taken" ] } }
Please tell me how to parse the particular data from the JSON data.
Thanks in advance!!!!
You can use below method to parse your data.
private String parseJsonData(String jsonResponse) {
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONObject errorJsonObject = jsonObject.getJSONObject("errors");
JSONArray jsonArray = null;
//has method
if (errorJsonObject.has("password")) {
jsonArray = errorJsonObject.optJSONArray("password");
} else if (errorJsonObject.has(" signature")) {
jsonArray = errorJsonObject.optJSONArray("signature");
}
String errorMessage = jsonArray.getString(0);
return errorMessage;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
You can replace unwanted symbols like below code:
errorMessage.repalce("[","");
errorMessage.repalce("]","");
errorMessage.repalce("/"","");
You can use Google's Gson library to do that using the following steps:
Add dependency in your build.gradle(Module:app) file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
For latest version of gson library, click here
To parse JSON string to an object use the code below:
Gson gson = new Gson();
// I'm fetching my session stored JSON string
// You can fetch as per your requirement
String jsonStr = session.getJsonStr();
MyObject myObject = (MyObject) gson.fromJson(jsonStr, MyObject.class);
And if you need to convert an object to a JSON string, you can use the below code:
// I'm fetching my session stored Object here
// You can fetch as per your requirement
MyObject myObject = session.getMyObject();
String jsonStr = gson.toJson(myObject);
Make sure you design your object appropriate for the JSON string to match the data types. If you are not sure of the data types in the JSON, you can use this site or any parse and view website to view them.
Hope it helps!
Just try this,
try {
String tost = null;
JSONObject object = new JSONObject(json);
JSONObject errorObject = object.getJSONObject("errors");
if (errorObject.has("password")){
tost = "password "+errorObject.getJSONArray("password").get(0).toString();
} else if (errorObject.has("signature")){
tost = "signature "+errorObject.getJSONArray("signature").get(0).toString();
}
Toast.makeText(MainActivity.this, tost, Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}

How to parse JSON Array in Array with Volley?

I'm trying to parse json from my website.
JSON: https://www.yemeklerimiz.com/?json=get_category_posts&id=6
There is 2 array in json. I can not parse posts array because before coming category array.
My Volley:
public void getPosts() {
String url = Constant.baseUrl+"?json=get_category_posts&id="+getIntent().getStringExtra("CAT_ID");
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray datas = jsonObject.getJSONArray("0");
for (int i = 0; i < datas.length(); i++) {
PostsModel postsModel = new PostsModel();
JSONObject jo = datas.getJSONObject(i);
String id = jo.getString("id");
String url = jo.getString("url");
String title = jo.getString("title");
Log.d("IMAGEUR", url);
postsModel.setID(id);
postsModel.setImageURL(url);
postsModel.setTitle(title);
postsModelArrayList.add(postsModel);
postsAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
This not work. What can I do to get JSONObjects which in posts array?
While I agree with saeedata's answer, I would like to explain you how you could get this code working in its current state and without Retrofit. I think it will better help you understand how JSON works.
So what you have here is:
The main JSON Object which is your response, and we can consider this the root.
Inside this "response" JSON Object, you have fields such as "count" and "pages", and also another field that is a JSON Array called "posts". This "posts" field contains various other JSON Objects in itself.
Following code snippet shows how to retrieve the posts objects and retrieve the fields in it.
JSONObject responseJSON = new JSONObject(response);
// Retrieve the posts JSON array from the response
JSONArray postsArray = jsonObject.getJSONArray("posts");
for (int i = 0; i < datas.length(); i++) { //loop to iterate in JSON array
//retrieve the single postObject in array
JSONObject postObject = postsArray.getJSONObject(i);
//get fields from the postObject
String id = postObject.getString("id");
String url = postObject.getString("url");
String title = postObject.getString("title");
Log.d("Title for " + i.toString(), title);
}
The output will be the following:
Title for 0: Unsuz Şekersiz Cheesecake
Title for 1: Hurmalı Şekersiz Browni
Title for 2: Kırmızı Meyveli Pratik Cheesecake
Title for 3: Tropikal Blondie
Title for 4: Glutensiz Şekersiz Çikolatalı Muzlu Kek
Title for 5: Starbucks Havuçlu Kek
Title for 6: Çikolatalı Dondurma
Title for 7: Saray Helvası
that's very simple with JSON tools like GSON or LoganSquare , ... . you must first create a model that fields have annotations then create a builder and finally convert your raw JSON string to model,
you can see an example in this link ;
I suggest use retrofit instead Volley because is very simple and faster than Volley

Json Parsing in Android with multiple same rows

Well,it is simple yet I am finding confused to extract the info.Could you give a look here:
formatted JSON Data
[
{
"catalogName":"a",
"categoryName":"aa",
"subCategoryName":"aaa",
"price":888.0,
},
{
"catalogName":"b",
"categoryName":"bb",
"subCategoryName":"bbb",
"productName":"hjb",
"price":9.0,
}
]
I would be printing this in my android app.Thanks
Here is how I do in my code:
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
// Check StatusLine result ....
// Convert response to a JSon Array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(baos);
baos.close();
JSONArray jsonArray = new JSONArray(baos.toString())
for(int i = 0; i < jsonArray.length(); ++i)
{
// Extract values from JSON row:
JSONObject jsonObject = jsonArray.getJSONObject(i);
String catalogName = jsonObject.has("catalogName") ? jsonObject.getString("catalogName") : "";
String categoryName = jsonObject.has("categoryName") ? jsonObject.getString("categoryName") : "";
String subCategoryName = jsonObject.has("subCategoryName") ? jsonObject.getString("subCategoryName") : "";
String productName = jsonObject.has("productName") ? jsonObject.getString("productName") : "";
double price = jsonObject.has("price") ? jsonObject.getString("price") : 0.;
// Do stuff with data:
...
}
Please note that if a row misses a value (like productName) you must handle it. In the example I assign a default value but maybe it's not the best choice.
JSONArray jsonArray=new JSONArray("YOUR_JSON_ARRAY_NAME"); //Must be case sensitive
for(int i=0;i<jsonArray.length();i++){
JSONObject current_job= jsonArray.getJSONObject(i);
String catalogName= current_job.getString("catalogName");
//same for other fields. KEY must be case sensitive
...
...
}
This is a JSONArray :-) Parse it with this:
String json = /** your JSON **/
JSONArray array = new JSONArray(json);
And now you can take the data out of the object with getJSONObject(int index) :-)
I suggest using a JSON parsing library, such as Gson. It is fast and very simple to use.
https://github.com/google/gson
If you have a following class:
class Catalog{
private String catalogName;
private String categoryName;
private String subCategoryName;
private String productName;
private double price;
/** Getter, setters, optional: toString, constructor... **/
}
To parse it simply call:
Type listType = new TypeToken<List<Catalog>>() {}.getType();
List<Catalog> yourList = new Gson().fromJson(YOUR_JSON_STRING, listType);
Instead of this "confusing" code for listType you can use also Class (see documentation), but this is not possible in your case, as provided JSON format is a direct list of elements, it is not wrapped. For using a class you would have to wrap this JSON with another element.

Parsing JsonArray With JsonObject

I have some JSON with the following structure:
{
"items":[
{
"product":{
"product_id":"some",
"price_id":"some",
"price":"some",
"title_fa":"some",
"title_en":"Huawei Ascend Y300",
"img":"some",
"has_discount_from_price":"0",
"discount_from_price":null,
"type_discount_from_price":null,
"has_discount_from_product":"0",
"discount_from_product":null,
"type_discount_from_product":null,
"has_discount_from_category":"0",
"discount_from_category":null,
"type_discount_from_category":null,
"has_discount_from_brand":"0",
"discount_from_brand":null,
"type_discount_from_brand":null,
"weight":null,
"features":[
{
"feature_value":"#000000",
"feature_id":"some",
"feature_title":"some"
},
{
"feature_value":"some",
"feature_id":"1652",
"feature_title":"some"
}
]
},
"number":1,
"feature_id":"56491,56493",
"price_inf":{
"has_discount":0,
"discount_type":0,
"final_price":"400000",
"value_discount":0
},
"cart_id":13
}
]
}
I'm trying to access the elements "product_id" and "price_id" with the following Java code:
try{
JSONArray feedArray=response.getJSONArray("items");
for (int i=0;i<feedArray.length();i++){
JSONObject feedObj=feedArray.getJSONObject(i);
JSONObject pro=feedObj.getJSONObject("product");
Product product = new Product();
product.setPrice(pro.getDouble("price_id"));
product.setTitle_fa(pro.getString("price_id"));}}
but i see product not found error.what is wrong in my parser?
First of all your JSON is valid. So no worries there.
Now regarding your problem, because you haven't posted the logs so I can't tell what the exact problem is. But using this code snippet you can get the desired values.
try {
JSONArray itemsJsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++){
JSONObject itemJsonObject = itemsJsonArray.getJSONObject(i);
JSONObject productObject = itemJsonObject.getJSONObject("product");
String productId = productObject.getString("product_id");
String priceId = productObject.getString("price_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Validate and create Pojo for your json here
use
Data data = gson.fromJson(this.json, Data.class);
follow https://stackoverflow.com/a/5314988/5202007
By the way your JSON is invalid .
you are getting a json object from your response not json array you need to make following changes
JSONObject temp =new JSONObject(response);
JSONArray feedArray=temp.getJSONArray("items");
Try converting response string to JSONObject first
try{
JSONObject temp =new JSONObject(responseString); // response is a string
JSONArray feedArray=.getJSONArray("items");
....
}
You may try to use GSON library for parsing a JSON string. Here's an example how to use GSON,
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

How to parse JSON with any key on android?

I want to parse JSON with any key on Android.
JSON data consists of any key, array or values.
Here are JSON data and my working code.
I want to put JSON data into a class by using JSON parsing.
JSON data :
{
"d520c8c17c8e":
{ "id":"25689123",
"number":"0e31b1994"
},
"d183c6e9913d":
{
"id":"25689123",
"number":"0e31b1994"
},
"content":"8090986565488990",
"text":"hello",
"status":"ok"
}
My code :
public static MyInfo getMyInfo(JSONObject json) {
MyInfo info = new MyInfo();
if (json == null)
return null;
try {
info.setContent(json.getString("content"));
info.setText(json.getString("text"));
info.setStatus(json.getString("status"));
ArrayList<MyList> mylists = new ArrayList<MyList>();
JSONArray panels = json.getJSONArray(????????????);
for(int i=0;i < panels.length();i++){
JSONObject e2 = panels.getJSONObject(i);
MyList info_list = new MyList();
info_list.setId(e2.getString("id"));
info_list.setNumber(e2.getString("number"));
info_list.add(info_answer);
}
info.setList(info_list);
} catch (JSONException e) {
}
return info;
}
please help me.
Yes this is possible.
Put the JSON you receive in a JSONObject. You can loop trough the keys and get the values out of it.
Example:
//Create json object from string
JSONObject newJson = new JSONObject(json);
// Get keys from json
Iterator<String> panelKeys = newJson.keys();
while(panelKeys.hasNext()) {
JSONObject panel = newJson.getJSONObject(panelKeys.next()); // get key from list
String id = panel.getString("id");
String number = panel.getString("number");
}
I hope this is what you were looking for

Categories

Resources