I obtain a JSONObject from my server in my Android application through a service and in order to send to my activity I convert JSONObject to a string with
String myjson= gson.toJson(object);
b.putString("json", myjson);
And transfer the string to my activity where I recreate the JSONObject from String
Gson gson = new Gson();
JSONObject jobj = gson.fromJson(mydata, JSONObject.class);
JSONArray jarray = jobj.getJSONArray("myitems");
My JSON is as below
{"myitems":[{"event_id":"1","title":"Music launch party at makeover","description":"Music Launch function at Makeover","store_id":"2","user_id":"1","category_id":"1","submittedby":"store","start_date":"2015-02-03 09:00:01","end_date":"2015-02-03 20:00:00","price":"1000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.693771","add_lon":"76.76486","distance":"10.329089177806534"},{"event_id":"2","title":"The Bacardi party at the New year bash","description":"Altius organizes a new year bash at their Night House.","store_id":"2","user_id":"1","category_id":"3","submittedby":"user","start_date":"2015-02-05 17:08:40","end_date":"2015-02-05 22:08:48","price":"2000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.69461","add_lon":"76.76176","distance":"10.575941394542852"}]}
But I am getting error on getting jsonarray from the jsonobject. what should be the right way to obtain the jsonarray from the jsonobject or what wrong I am doing here.
Try the following :
Create a class containing a replica of the json objects
public class MyItem {
String event_id;
String title;
String description;
String store_id ;
String user_id;
String category_id;
String submittedby;
String start_date;
String end_date;
String price;
String gallery_1;
String gallery_2;
String gallery_3;
String add_lat;
String add_lon;
String distance;
public MyItem() {
}
}
In your case myjson is the string containing the json reply..so
JSONArray array = null;
try {
JSONObject jsonResp = new JSONObject(myjson);
array = jsonResp.getJSONArray("myitems");
} catch (JSONException e) {
e.printStackTrace();
}
Then you can iterate through the array and store objects in your custom class like so :
for(int i = 0; i < array.length(); i++){
JSONObject json2 = null;
try {
json2 = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
MyItem myItem = gson.fromJson(json2.toString(), MyItem.class);
//Do whatever you want with the object here
}
Related
I print this json array in my android
It includes an array inside of an array
What is the android code?
This is my php output
[{"result":"true","user":[{"id":"26","name":"Manali Ashar","email":"123","password":"manali.ashar19#gmail.com","address":"chital road","city":"amreli","contact":"9402312345","qualification":"M.D","experience":"2","department":"Pediatric","age":"22","from_time":"05:15:00","to_time":"07:15:00","status":"1","current_date_time":"2016-04-02 07:18:26"}]}]
String data="[{"result":"true","user":[{"id":"26","name":"Manali Ashar","email":"123","password":"manali.ashar19#gmail.com","address":"chital road","city":"amreli","contact":"9402312345","qualification":"M.D","experience":"2","department":"Pediatric","age":"22","from_time":"05:15:00","to_time":"07:15:00","status":"1","current_date_time":"2016-04-02 07:18:26"}]}]";
try
{
JSONArray array=new JSONArray(data);
JSONObject jsonObject=array.getJSONObject(0);
String returnword=jsonObject.getString("return");
JSONArray users=jsonObject.getJSONArray("user");
for(int i=0;i<users.length();i++)
{
JSONObject object=users.getJSONObject(i);
String id=object.getString("id");
String name=object.getString("name");
String email=object.getString("email");
String password=object.getString("password");
String address=object.getString("address");
String city=object.getString("city");
String contact=object.getString("contact");
String qualification=object.getString("qualification");
String experience=object.getString("experience");
String department=object.getString("department");
String age=object.getString("age");
String from_time=object.getString("from_time");
String to_time=object.getString("to_time");
String status=object.getString("status");
String current_date_time=object.getString("current_date_time");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
This is the simple way to parse any kind of json.
try to remove all array brackets [ ] because you need JSON Object only not array of json object. then data will look like
{"result":"true","user":{"id":"26","name":"Manali Ashar","email":"123","password":"manali.ashar19#gmail.com","address":"chital road","city":"amreli","contact":"9402312345","qualification":"M.D","experience":"2","department":"Pediatric","age":"22","from_time":"05:15:00","to_time":"07:15:00","status":"1","current_date_time":"2016-04-02 07:18:26"}}
now android code:
try {
JSONObject json = new JSONObject(result);
JSONObject user= json.getJSONObject("user");
String name= user.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
//send response
JSONArray jsonArray = JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if(!jsonObject.isNull("result")){
String result = jsonObject.getString("result");
if(result.equals("true")){
JSONArray userArray = jsonObject.getJSONArray("user");
for(int j=0; j<userArray.length(); j++){
jsonObject = userArray.getJSONObject(j);
String id = isJsonValid(jsonObject, "id");
String name = isJsonValid(jsonObject, "name");
String email = isJsonValid(jsonObject, "email");
String password = isJsonValid(jsonObject, "password");
String address = isJsonValid(jsonObject, "address");
String city = isJsonValid(jsonObject, "city");
String contact = isJsonValid(jsonObject, "contact");
String qualification = isJsonValid(jsonObject, "qualification");
String experience = isJsonValid(jsonObject, "experience");
String department = isJsonValid(jsonObject, "department");
String to_time = isJsonValid(jsonObject, "to_time");
String age = isJsonValid(jsonObject, "age");
String from_time = isJsonValid(jsonObject, "from_time");
String status = isJsonValid(jsonObject, "status");
String current_date_time = isJsonValid(jsonObject, "current_date_time");
}
}else{
//do something
}
}
}
}catch (JSONException je){
je.printStackTrace();
}
public String isJsonValid(JSONObject jsonObject, String key) throws JSONException {
//check key is present or not
if(!jsonObject.isNull(key)){
return jsonObject.getString(key);
}else{
return "N/A";
}
}
You can make use of Gson library
Step 1: Create the POJO for the json data
public class Data {
public String result;
public List<User> user;
}
public class User {
public String status;
public String department;
public String password;
public String contact;
public String city;
public String id;
public String qualification;
public String email;
public String address;
public String from_time;
public String name;
public String age;
public String current_date_time;
public String experience;
public String to_time;
}
Step 2: Parse the JSON using Gson library
final Gson gson = new Gson();
Since it's a array of data, we need to get a List like this from the json string
List<Data> response = gson.fromJson(JSON_DATA, new TypeToken<List<Data>>() {}.getType());
Step 3: Get the values
Data data = response.get(0);
User user = data.user.get(0);
And print the result likewise
Log.d("JsonExample","Name: " + user.name);
...
...
I have json data as mentioned below.
{
"data":[
{
"Products":{
"id":"86",
"pname":"mi4",
"pcat":"9",
"subcat":"8",
"seccat":"0",
"oproduct":"1",
"pdetails":"Good phone",
"pprice":"10000",
"pdiscount":"10",
"qty":"1",
"qtytype":"GM",
"dcharge":"40",
"pimage":null,
"sname":"Easydeal",
"sid":"1100",
"size":"",
"pincode":""
}
}
]
}
I can identify array as getJSONArray("datas"). But I want to get pname and sname values.
Just reach the object
JSONObject resp=new JSONObject("response");
JSONArray data=resp.getJSONArray("data");
now if you want to get object at a particular index(say '0')
JSONObject objAt0=data.getJSONObject(0);
JSONObject products=objAt0.getJSONObject("products");
String pName=products.getString("pname");
you can similarly traverse the array
for(int i=0;i<data.lenght();i++){
JSONObject objAtI=data.getJSONObject(i);
JSONObject products=objAtI.getJSONObject("products");
String pName=products.getString("pname");
}
To get the to the key "Products" you should do:
JSONObject productsObject = YOUROBJECTNAME.getJSONArray("data").getJSONObject(0).getJSONObject("Products");
Then to get the values in productsObject you should do:
productsObject.getString("id");
productsObject.getString("pdetails");
And so on.
Try out the following code:
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("data");
JSONObject object1 = array.getJSONObject(0);
JSONObject products = object1.getJSONObject("Products");
int id = object1.getInt("id");
String pname = object1.getString("pname");
This is how you get pname and sname:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
try {
jsonArray = jsonObject.getJSONArray("data");
for(int counter = 0; counter <jsonArray.length(); counter++){
JSONObject jsonObject1 = jsonArray.getJSONObject(counter);
JSONObject products = jsonObject1.getJSONObject("Products");
String pname = products.getString("pname");
String sname = products.getString("sname");
}
} catch (JSONException e) {
e.printStackTrace();
}
PS: Poor JSON structure :)
This is My Json String
{"Damages":[{"id":15,"rf_no":5,"state":"Print5","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "},{"id":36,"rf_no":7,"state":"Print7","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "}]}
But in Android Application its Showing No Value For Damages
This is My Android Code
JSONArray jArray = new JSONArray(json.getString("Damages"));
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
final String id = c.getString("id");
String dmg_no =
c.getString("dmg_no");
String firm_name = c.getString("firm_name");
final String rf_no = c.getString("rf_no");
String town=c.getString("town");
String date=c.getString("date");
String State=c.getString("state");
}
Help Me Please. And Thanx In Advance.
You can try this code, to parse your json data:
try
{
JSONObject jsonObj=new JSONObject(result); // result=JSON string
if(jsonObj.has("Damages"))
{
JSONArray arrayObj=jsonObj.getJSONArray("Damages");
for(int i=0;i<arrayObj.length();i++)
{
JSONObject childArray=arrayObj.getJSONObject(i);
Log.e("", "ID "+childArray.getString("id"));
Log.e("", "Ref No"+childArray.getString("rf_no"));
// similarly you can parse rest of your tags
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this helps you.
This is your mistake : JSONArray jArray = new JSONArray(json.getString("Damages"));
you are trying to get the string by name "Damages" and coverting it to JSONarray. But what you have to do is you have to convert your string to JSONObject first and then get the array named "Damages" from that json object.
Try this
String jsonString = {"Damages":[{"id":15,"rf_no":5,"state":"Print5","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "},{"id":36,"rf_no":7,"state":"Print7","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "}]}
try {
JSONObject jsonObject=new JSONObject(jsonString);
JSONArray damageArray=jsonObject.getJSONArray("Damages");
for(int i=0;i<damageArray.length();i++)
{
JSONObject obj=damageArray.getJSONObject(i);
String dmg_no = obj.getString("dmg_no");
String firm_name = obj.getString("firm_name");
final String rf_no = obj.getString("rf_no");
String town=obj.getString("town");
String date=obj.getString("date");
String State=obj.getString("state");
}
} catch (JSONException e) {
e.printStackTrace();
}
This is the problem line
JSONArray jArray = new JSONArray(json.getString("Damages"));
What are you doing is telling the program to find value of String Damages and then get array with name of that value - but there is no array called like that! Your array is already named, and the name is Damages.
To get the array you simply do
JSONArray jArray = json.getJSONArray("Damages");
assuming json is the main response you are getting
i have this json:
[{"id":"1","name":"john"},{"id":"2","name":"jack"},{"id":"3","name":"terry"}]
how i can parse this? i have to use a loop for extracting each group? for simple jsons i use this code:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
but now i have to parse my new json. please help me
It should be like this:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject json = jsonArray.getJSONObject(index);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
}
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
Of course you should return an array of names or whatever you want..
This is meant to be parsed by a JSONArray, and then each "record" is a JSONObject.
You can loop on the array and then retrieve the JSON String of each record with the getString(int) method. Then use this string to build a JSONObject, and just extract values like you do now.
You can use the following code:
public static void parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String name = json.getString("name");
String id = json.getString("id");
//Store strings data or use it
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
You need to modify the loop to store or use the data.
Hope it helps.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON Parsing in Android
As I find out I need to use Gson class to parse json to Java object in android. It's quite easy to parse simple varables or array, but I don't know how to parse more complex json string, my json look like this:
{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]}
Can anyone help me how to do this?
//Model class
class Model {
private String mId ;
private String mScore;
public Model (String id , String score){
mId = id ;
mScore= score
}
//getter and setter
}
// in your class
private ArrayLsit getLsit(String str){
ArrayLsit<Model > list = new ArrayLsit<Model>();
// getting JSON string from URL
JSONObject json = new JSONObject(str);
try {
// Getting Array of Contacts
contacts = json.getJSONArray("data");
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String score= c.getString("score");
list.add(new Model(id ,score))
}
} catch (JSONException e) {
e.printStackTrace();
}
return list
}
Check out the code..
Result = jsonObject.getString("data");
jsonArray = new JSONArray(Result);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
try {
jsonObject.getString("Id");
} catch (Exception ex) {
cafeandbarsList.add(null);
ex.printStackTrace();
}
}
Thanks
create to class for json,
Gson gson = new Gson();
Jsondata jsonddata = gson.fromJson(response, Jsondata .class);
=====
JsonData.jave
#SerializedName("selected_id")
public String sid;
#SerializedName("data")
public List<data> dalalist;
===
data.java
#SerializedName("id")
public String id;
#SerializedName("score")
public String score;