JSON exctract key for fill Spinner - android

I would like to extract into two separate array the key "desc" and "type" in my JSON file.
I get the file from an ftp site and I don't know how many entry there are.
After I have the String Array, I would like to fill a Spinner by the "desc" value.
How can do that?
this is my JSON file
{
"Pagnerine":[{
"Cialda":[{
"userId":1,
"desc":"Sottozero/Estate",
"type":"ct"
},
{
"userId":2,
"desc":"Piccolo/Primavera",
"type":"ct"
},
{
"userId":3,
"desc":"Medio",
"type":"ct"
},
{
"userId":4,
"desc":"Grande",
"type":"ct"
}
],
"Cartone":[{
"userId":1,
"desc":"16B",
"type":"ct"
},
{
"userId":2,
"desc":"17",
"type":"ct"
},
{
"userId":3,
"desc":"34",
"type":"ct"
},
{
"userId":4,
"desc":"20",
"type":"ct"
}
]
}
],
"Cucchiaini":[],
"Vaschette":[],
"Zuccheri":[],
"versione":"100"
}
i have tried to implement this code for obtain how many entry (desc or type) there are, but fail because count only the first part "Cialda" and "Cartone"
Iterator<String> iter = jObj.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray jArray = jObj.getJSONArray(key);
// looping through
entry += jArray.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

I would suggest implementing an easier to maintain solution for this so you can get it into easy to use POJOs and adapt to potential changes later on. My preferred approach is to use [GSON}(https://code.google.com/p/google-gson/), but there's also Jackson.
Take a look at the GSON User Guide for specifics, but basically here's the concept.
Let's say that my JSON is the following:
JSON
{ "items" :
[
{
"type" : "food",
"name" : "Tacos"
},
{
"type" : "food",
"name" : "Bacon"
},
{
"type" : "food",
"name" : "Beer"
},
]
}
I would create the following objects:
Items.java
public class Items {
List<Item> items;
}
Item.java
public class Item {
String type;
String name;
}
Then I would simply do the following to create my Items object once I got the JSON.
Items deliciousFoodStuffs = gson.fromJson(json, Items.class);
This would result in me having deserialized my JSON into POJOs which I can use to my hearts content.
Let's say that I don't want to map via the field names but instead map to Java fields named differently, I would do the following instead:
Item.java
public class Item {
#SerializedName("type")
String typeValue;
#SerializedName("name")
String nameValue;
}
Using the same call as before
Items deliciousFoodStuffs = gson.fromJson(json, Items.class);
I will receive the same result with this, expect my variables are named differently.
Note: Beer, Bacon, and Tacos are all delicious and not necessarily organized in the order of deliciousness.

The code you've posted doesn't match your objective in the question. But to answer the issue of why entry only counts the first two elements (and assuming jObj is a valid JSONObject containing the Pagnerine element) Try this:
for(int i = 0; i < jObj.length(); i++) {
JSONObject childObject = new JSONObject(jObj.get(i).toString());
entry += childObject.length();
}
entry should now contain the total number of elements there are in your JSON file. The change is to iterate through each of the parent elements (in this case Cialda and Cartone), and for each of these elements count the number of child elements.
Edit
As per your comment, this can be amended easily to get a count of the parents, and children:
for(int i = 0; i < jObj.length(); i++) {
parentCount += jObj.length();
JSONObject childObject = new JSONObject(jObj.get(i).toString());
childCount += childObject.length();
}

Related

Parsing inner int json object in android

I have already checked other posts of Stack Overflow regarding Json data parsing but did not find the solution to parse inner Json int objects.
I am getting the following response from a web service.
{
"counter":[
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
]
}
Where "1", "2" and "n" are ids and json object size changes according to the data. I am able to parse the above response till JsonObect using following code:
JsonArray jsonArray = GetJson_.getArray(response, "counter");
if (jsonArray != null) {
JsonObject object = jsonArray.get(0).getAsJsonObject();
}
and my jsonObject now looks like
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
But I am stuck at how to parse the JsonObject which is dynamic.
Please help.Thanks in advance.
hey you may use HashMap<> for parse dynamic key response for this check this link, other way you may use Iterator which i done below :
JSONObject jsonObject= m_jArry.getJSONObject(0);
Log.e("ad","--------"+jsonObject.toString());
Iterator keys = jsonObject.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Hope this will helpful to you.

How to get a corresponding key in a json object and put it in my recyclerView onBindViewHolder

I have a json array, jsonArray, like:
[{
"phone_number": "+123456",
"name": "Bob"
},
{
"phone_number": "+234567",
"name": "Tom"
},
{
"phone_number": "+345678",
"name": "Jim"
},
{
"phone_number": "+4567890",
"name": "Jane"
},
{
"phone_number": "+5678901",
"name": "Sally"
}
]
In my onBindViewHolder I want to check if phone_number value in the json array matches username and then if there is a match then in the viewHolder.phone_user_name set the text to the corresponding value in "name" of the json array.
But all I get in my recyclerView for each cell is user : (blank)
Here's what I've tried so far:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
SharedReview r = the_Shared_reviews.get(position);
//username is in fact a phone number from the db
String username = r.getUsername();
String phone_user_name = "";
int matching = jsonArray.length();
for (int i = 0; i < matching; i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
if (object.getString("phone_number").contains(username))
{
phone_user_name = (object.getString("name"));
}
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//I want to set the text to Bob, Tom, or whatever corresponding
// phone number matches username
((ReviewHolder) viewHolder).phone_user_name.setText("user :" + phone_user_name);
}
You should create a list of Object of (Phone Number, Name) and bind it to the recycler view. in "onBindViewHolder()", you can find the corresponding object from the list which contains both fields.
I'm not sure what value is supposed to be in the SharedReview class under the username variable, but I'm assuming it's a name, not a number.
However, you are testing if your json array item named "phone_number", which in your example is an actual phone number, contains the username. Which is assumably a name.
You should replace:
if (object.getString("phone_number").contains(username))
{
phone_user_name = (object.getString("name"));
}
With:
if (object.getString("name").equals(username))
{
phone_user_name = (object.getString("name"));
}

Get json array length and looping

So I have a json response from web service like this
{
error: false
types: [2]
-0: {
card_type_id: 5
category: "Food & Beverages"
}
-1: {
card_type_id: 8
category: "Entertaiment"
}
}
what I want to do is to get the number inside json array "types" and use it to looping to set the value of arraylist that will be use in listview, but my code seems and cannot get the json array length, this is my code
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
JSONArray types = obj.getJSONArray("types");
for(int i=0; i<types.length();i++)
{
JSONObject a = types.getJSONObject(i);
int ct_id = a.getInt("card_type_id");
String category = a.getString("category");
CardType ct = new CardType();
ct.setTypeId(_ct_id);
ct.setTypeCategory(_category);
categoryArray.add(ct);
}
}
Can anyone help me? Thanks before
This is what your JSON response probably should look like (note also that keys and string values should be sorrounded by double-quotes):
{
"error": false,
"types": [
{
"card_type_id": 5,
"category": "Food & Beverages"
},
{
"card_type_id": 8,
"category": "Entertaiment"
}
]
}
The JSONArray "types" in this example has a length (types.length()) of 2. Now you can implement your for-loop and should get the expected results.
actually it's just my fault to see the json from advanced rest client, i use the json menu and the app automatically correct the json and become invalid, after i change to raw menu i can see the actual json and correct the code

Android code For Following JSON Pattern

Want Android Code For Following JSON Format...Bit Confused How to fetch value of array For Following Pattern..
{
"params": [
{
"answer_data_all": [
{
"id": "5",
"question_id": "14"
}
],
"form_data_all": [
{
"id": "1",
"name": "form 1"
}
]
}
]
}
You just have some nested JSONArray and JSONObject. Assuming you have this response in string format all you have to do is create JSONObject from that string and then extract what you need. As someone mentioned [ ] encloses JSONArray while { } encloses JSONObject
JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");
String id = formData.getJSONObject(0).getString("id");
You should be able to extract all the values doing something like this. Although I will say I think the formatting is odd. You're using single member arrays that just contain other objects. It would make much more sense to either use one array to hold all the object or just separate JSONObject. It makes it much easier to read and easier to parse.
Parsing a JSON is fairly simple. You could use GSON library by Google for example. Below is an example I wrote for your object/model:
class MyObject{
ArrayList<Params> params;
class Params {
ArrayList<AnswerData> answer_data_all;
ArrayList<FormData> form_data_all;
class AnswerData {
String id;
String question_id;
}
class FormData {
String id;
String name;
}
}
}
And then get an instance of your object with:
MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);
JSONArray feed = feedObject.getJSONArray("params");
for(int i = 0; i<feed.length(); i++){
JSONArray tf = feed.getJSONArray(i);
for (int j = 0; j < tf.length(); j++) {
JSONObject hy = tf.getJSONObject(j);
String idt = hy.getString("id");
String name = hy.getString("name");
}
}
**NOTE: the 'feedObject' variable is the JSONObject you are working with..Although this your type of JSON feed is kinda mixed in terms of string names and all but this should do for now..

Android - json parsing

I have a JSON as shown below:
{
"places": [{
"name": "Ankola",
"slug": "ankola",
"category": "beach",
"distance": "521",
"travel_time": "8 hrs, 2 mins",
"days": "3",
"latitude": "14.669456",
"longitude": "74.300952",
"weather": "Summer 21\u00b0-36\u00b0C, Winter 12\u00b0-35\u00b0C",
"todo": "Baskal gudda, Nadibag, Shedikuli, Keni, Belekeri",
"about": "Ankola is a small town surrounded by numerous temples. It is in line with Arabian sea. Ankola is famous for its native breed of mango called ishaad and for cashews harvesting.",
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}]
}
I know how to fetch key - value pairs, but i dont know how to parse array inside json to form a string array(image - in my case)
To summarize i want something like this:
I have 5 image names under "image" tag, i want them in a string array. How can i do this?
Use :
JSONArray images = yourJSONObject.getJSONArray("image");
for(int i = 0; i < images.length(); i++){
String image = images.getString(i);
}
This should do the trick as I remember.
Here you go:
JSONArray ja = whatEverYourJsonObject.getJSONArray("image");
for(int i=0; i<ja.length(); j++){
String name = ja.getString(i);
}
You first have to convert the JSON string to a Java object (JSONObject). Then, you obtain your JSONArray and iterate over it.
Example:
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject (jsonString);
JSONArray images = itemObj.getJSONArray ("images");
int length = images.length ();
for (int i = 0; i < length; i++)
Log.d ("Image Filename", images.getString (i));
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: Now I see that your JSON is invalid - you have an object for each image and that object contains only the value part of the data. An example of a valid images array would be as follows:
{
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}
I would suggest:
Create your own class which describes your data structure defined
by those json object. As a last resort you can even generate Java
class based on JSON string - look at
jsongen
When you will have your own Java class (let's say MyClass) you can easily parse JSON to your generated Java class using GSON, like:
MyClass myClass = gson.fromJson(jsonString, MyClass.class);

Categories

Resources