How create a POST with JsonArray in body - android

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.

Related

json data fetching android

How do I fetch this data using json. I have tried this but not working. Im very much confused about how to fetch the below data. Any help appreciated
{
"sftid": [
"sfta"
],
"todate": 205618.268,
"today": 5307.174,
"sfta": 5093.717,
"sftb": 213.457,
"sftc": 0,
"cropday": 21,
"crushingday": 21,
"vtractor": 4535.075,
"vtruck": 532.687,
"vbcart": 239.412,
"yestitons": 6374,
"ytractor": 248,
"ytruck": 90,
"ybcart": 40,
"ycart": 48,
"hr1": 515.043,
"hr2": 625.651,
"hr3": 706.789,
"hr4": 626.796,
"hr5": 630.639,
"hr6": 608.053,
"hr7": 604.559,
"hr8": 776.187
}
JSONObject jobject = new JSONObject(response);
JSONObject jsonObj = jobject.getJSONObject("todate");
You can do something like this
JSONObject jobject = new JSONObject(response);
then
double todate = jobject.getDouble("todate");
and so on as per the data type
or simply you can use http://www.jsonschema2pojo.org/ which will help you to convert your json data to a model class which you can use to fetch the data easily.
For this you need to use Gson library.
So suppose you created class with above link as "Myresponse" the you can use it as
Gson gson = new Gson();
Myresponse data = gson.fromJson("<your json resopnse>",Myresponse.class);
I have added screenshot for the settings you need to do on jsonschema2pojo website
As you see your response contains one JSONObject which contains many elements, First element is an JSONArray rest can be taken as a double/String.
It goes as follows :
JSONObject json = new JSONObject(response);
JSONArray sftid_array = json.getJSONArray("sftid");
ArrayList<String> sftid = new ArrayList();
for(int i = 0; i < sftid_array; i++) {
sfid.put(sftid_array.getString(i));
}
double todate = json.getDouble("todate");
double today = json.getDouble("today");
double sfta = json.getDouble("sfta");
double sftb = json.getDouble("sftb");
.
.
.
and so on
You can also use Array to store data of JSONArray. Don't forget to put it in try catch as it may throw JSONException.
You could try:
JSONObject jobject = new JSONObject(response.toString());
JSONObject jsonObj = jobject.getJSONObject("todate");

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

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

how to build Below kind of JSON Format to post it as a request in android?

Ineed to post data in JSON format as shown below And the size of the array is not
constant. it depends on the user.
{
"info": [
{
"Name": "foo1",
"Number": 123
},
{
"Name": "foo2",
"Number": 124
},
{
"Name": "foo2",
"Number": 125
}
]
}
I tried to create in the following way
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText()).toString();
childObj.put("Number", etNumber.getText()).toString();
jArray.put(childObj);
parent.put("info",jArray);
but i'm unable to get it and I also tried in this way like example 6.1 but there is no method like add for JSONArray. So how can post my data. Please help me.
Thanks.
I'm not sure exactly what your question is but I'd typically do something like this to create the JSON string that you are looking for (the example below is using the org.json reference implementation from http://www.json.org/java/index.html):
JSONObject parent = new JSONObject();
JSONArray infoArray = new JSONArray();
for(int i = 0; i < SOMEARRAY.length; i++)
{
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText());
childObj.put("Number", etNumber.getText());
infoArray.put(childObj);
}
parent.put("info", infoArray);
String encodedJsonString = parent.toString();
I don't understand why you're calling toString() after putting stuff into childObj.
Anyway, this code should work:
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
try
{
//create first child
childObj
.put("Name", "foo1")
.put("Number", 123);
//insert it into the array
jArray.put(childObj);
//... repeat for all remaining elements
//attach the array to the parent
parent.put("info",jArray);
}
catch (JSONException e)
{
e.printStackTrace();
}
Then, to get your JSON as a string for POSTing just call parent.toString();

Categories

Resources