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
Related
{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am getting Json Response from the server, And mapping JSON data with Java class.
Here is code.
Gson gsonObj = new Gson();
AppointmentData appointmentData = gsonObj.fromJson(response, AppointmentData.class);
its working fine until response changes sometimes.
Here is response screenshot.
Now look at the response final_slots in response is sometimes as JSON Object and sometimes JSONArray. if final_slots is JSONArray then my Mapping code works, but if its is JSON Object then I have to change the logic. here is my code what I m doing in both cases
JSONObject JsonObjResponse = new JSONObject(response);
JSONObject jsonDataObj = JsonObjResponse.getJSONObject("data");
Object json = new JSONTokener( jsonDataObj.get("final_slots").toString()).nextValue();
/*******************************If response (final_slots) is JsonObject******************************/
if (json instanceof JSONObject) {
JSONObject jsonObj = jsonDataObj.getJSONObject("final_slots");
appointmentData=new AppointmentData();
AppointmentSettingData appointmentSettingData=new AppointmentSettingData();
JsonObjResponse.getString("data");
User userObj=new User();
JSONObject userJsonData= JsonObjResponse.getJSONObject("data").getJSONObject("user");
userObj.pk=userJsonData.getInt("pk");
userObj.unique_id=userJsonData.getString("unique_id");
userObj.fk_role=userJsonData.getInt("fk_role");
userObj.fk_status=userJsonData.getInt("fk_status");
userObj.fk_hospital=userJsonData.getInt("fk_hospital");
userObj.fk_department=userJsonData.getInt("fk_department");
userObj.fk_sub_department=userJsonData.getInt("fk_sub_department");
userObj.user_slug=userJsonData.getString("user_slug");
userObj.first_name=userJsonData.getString("first_name");
userObj.last_name=userJsonData.getString("last_name");
userObj.user_name_en=userJsonData.getString("user_name_en");
userObj.user_name_ar=userJsonData.getString("user_name_ar");
userObj.username=userJsonData.getString("username");
userObj.password=userJsonData.getString("password");
userObj.email=userJsonData.getString("email");
userObj.contact=userJsonData.getString("contact");
// userObj.qualification=userJsonData.getString("qualification");
userObj.mobile=userJsonData.getString("mobile");
userObj.appointment_duration=userJsonData.getInt("appointment_duration");
userObj.registration_date=userJsonData.getString("registration_date");
userObj.activation_code=userJsonData.getString("activation_code");
userObj.email_verified=userJsonData.getInt("email_verified");
userObj.device_token=userJsonData.getString("device_token");
userObj.device_type=userJsonData.getString("device_type");
userObj.device_id=userJsonData.getString("device_id");
userObj.created_at=userJsonData.getString("created_at");
userObj.updated_at=userJsonData.getString("updated_at");
// userObj.created_at=userJsonData.getString("created_by");
userObj.updated_by=userJsonData.getInt("updated_by");
appointmentSettingData.setUser(userObj);
appointmentData.setData(appointmentSettingData);
int i=0;
List<Slots> final_slots=new ArrayList<Slots>();
while(jsonObj.getJSONObject(""+i).has("start") && jsonObj.getJSONObject(""+i).has("end")){
Slots slot=new Slots();
slot.start=jsonObj.getJSONObject(""+i).get("start").toString();
slot.end=jsonObj.getJSONObject(""+i).get("end").toString();
final_slots.add(slot);
appointmentSettingData.setFinal_slots(final_slots);
appointmentData.setData(appointmentSettingData);
i++;
}
totalslots = final_slots.size();
totalslotLines = totalslots / 5;
} else if (json instanceof JSONArray) {
/*******************************If response (final_slots) is JsonArray******************************/
appointmentData = gsonObj.fromJson(response, AppointmentData.class);
totalslots = appointmentData.data.final_slots.size();
totalslotLines = totalslots / 5;
}
Issue:
when in response final_slots comes as json Object. As you can that when it final_slots is as jsonObject then I am getting inside JSON Object by the index as the name of JSON Object(i.e jsonObj.getJSONObject(""+i).get("start")). I am having issue when index is missing (you can see response upload image), because i am getting by the index, assuming that index will not miss in response. but I m fail here.
while(jsonObj.getJSONObject(""+i).has("start") && jsonObj.getJSONObject(""+i).has("end")){
Slots slot=new Slots();
slot.start=jsonObj.getJSONObject(""+i).get("start").toString();
slot.end=jsonObj.getJSONObject(""+i).get("end").toString();
final_slots.add(slot);
appointmentSettingData.setFinal_slots(final_slots);
appointmentData.setData(appointmentSettingData);
i++;
}
what I need:
I want to appointmentData object a compelete object which provide me all response either jsonArray in response or JSonobject in response.
I will be thankful to you for my assistance.
I want to send this json body to server using POST METHOD
{
"donatations": [
{
"campaignId": "string",
"name": "string",
"type": 0,
"donationValue": 0
}
],
"profileId": "string",
"creditCardId": "string",
"isPaidFees": true,
"isRequestDonatation": true
"amountFees": 0,
"totalDonationAmount": 0,
"institutionId": "string"
}
I tried many solutions available on web but most of them tell to format the string and sent to server. Is there any correct way to send this body to server?.
I usually do this to send simple Strings to server
JsonObject dados = new JsonObject();
dados.addProperty("profileId", sessionManager.getUsuario().getId());
dados.addProperty("name", scanResult.cardholderName.toString());
And send the JsonObject as Body of my POST
please help me. Thanks.
You can use the JsonObj/Array API to create one:
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i = 0; i < 10; i++){
JSONObject objFromArray = new JSONObject();
objFromArray.put("key", "value");
objFromArray.put("ke2y", "value");
array.add(objFromArray);
}
obj.put("child", array);
obj.put("normalObject", "another value");
You will have a object such:
{"child": [ {/**obj*/}, /** 9 more objs*/ ], "normalObject":"anther value" }
I typically use Spring and Java POJO's to send/receive data as you have mentioned. Create a new Spring Java application. Once you have a basic Spring application, you can now model your data structure with POJO's. Something like the following should work for your data structure:
public class Profile() {
private String profileId;
private String creditCardId;
private boolean isPaidFees;
private List<Donations> donations;
//etc. plus getters and setters
}
public class Donations(){
private String campaignId;
private String name;
private int type;
private float donationValue;
//etc. plus getters and setters
}
Now that you have your data structures defined in Java POJO's you can create a REST interface using spring that will map it for you. This can read in JSon and convert it to your POJO or it can get your POJO and return it as JSon.
#RequestMapping(value = "/getProfile", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Profile getProfile(#RequestBody Profile profile) {
System.out.println(profile.profileId);
return profile;
}
You don't need to create a pojo if you are only creating the object to post it. Here is a very simple way:
JSONObject mainObject = new JSONObject();
JSONArray array = new JSONArray();
JSONObject arrayItem = new JSONObject();
try {
//PUT VALUES TO THE ARRAYITEM.
//YOU WILL NEED TO LOOP HERE IF YOU HAVE MORE THAN 1 ITEM IN THE JSONARRAY
arrayItem.put("campaignId", "string");
arrayItem.put("name", "string");
arrayItem.put("type", 0);
arrayItem.put("donationValue", 0);
//PUT THE JSONOBJECT ITEM INSIDE THE JSONARRAY
array.put(arrayItem);
//PUT THE JSONARRAY INSIDE THE MAIN JSONOBJECT
mainObject.put("myArray", array);
//KEEP PUTTING THE REMAINING ITEMS INSIDE THE MAIN JSONOBJECT
mainObject.put("profileId", "string");
mainObject.put("creditCardId", "string");
mainObject.put("isPaidFees", true);
mainObject.put("isRequestDonatation", true);
mainObject.put("amountFees", 0);
mainObject.put("totalDonationAmount", 0);
mainObject.put("institutionId", "string");
} catch (JSONException e) {
e.printStackTrace();
}
Now you can send the mainObject normally the way you used to do it before.
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
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