hello i am trying to use a POST method of volley to get a string something like this
{"Date":"01-04-2017","PartyName":"Customer3","Supplier":"Supplier2",
"Items":[{"ItemNo":0,"ItemName":"a","Quantity":100,"DueDate":"01-04-
2017","Price":80,"Amount":80000}]}
here is my code:
JSONObject singleorder= new JSONObject();
try {
singleorder.put("Date",Get_date);
singleorder.put("PartyName",Get_partyname);
singleorder.put("Supplier", Get_supplier);
JSONArray arr = singleorder.getJSONArray("Items");
for(int i=0;i<arr.length();i++){
JSONObject obj = arr.getJSONObject(i);
//obj.put("ItemNo",Get_itemno);
obj.put("ItemName",Get_itemname);
obj.put("Quantity",Get_quantity);
obj.put("Price",Get_price);
obj.put("Amount",Get_amount);
}
//JSONArray item = new JSONArray("Items");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
when i run my code it, doesnt take the Array "item". it gives me the error:
org.sjon.JSONException:No value for Items.
where i am doing wrong?
JSONObject singleorder= new JSONObject();
try {
singleorder.put("Date",Get_date);
singleorder.put("PartyName",Get_partyname);
singleorder.put("Supplier", Get_supplier);
int loopSize = Get_No_items(); //Or just initialize it as 1 in your particular case
JSONArray arr = new JSONArray();
for(int i=0;i<loopSize;i++){
JSONObject obj = new JSONObject();
//obj.put("ItemNo",Get_itemno);
obj.put("ItemName",Get_itemname);
obj.put("Quantity",Get_quantity);
obj.put("Price",Get_price);
obj.put("Amount",Get_amount);
arr.put(obj);
}
singleorder.put("Items", arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Do something like this, it will be more error-free
class A implements Serializable{
private String name;
private B addresses[];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public B[] getAddresses() {
return addresses;
}
public void setAddresses(B[] addresses) {
this.addresses = addresses;
}}
class B implements Serializable{
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
And finally
{A a = new A();
a.setName("abc");
B addresses[] = new B[1];
addresses[0] = new B();
addresses[0].setAddress("xyz");
a.setAddresses(addresses);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(a);}
and it will produce JSON string like
{"name":"zafa","addresses":[{"address":"xyz"}]}
You can create json array like this
private JSONArray getJsonArray(ArrayList<Object> array) {
JSONArray jsonArray = new JSONArray();
if (array != null && array.size() > 0) {
for (int i = 0; i < array.size(); i++) {
JSONObject jsonObject = new JSONObject();
Object object = array.get(i);
try {
jsonObject.put(DESCRIPTION, object.getData());
jsonObject.put(IMAGE_URL, object.getAnotherData());
jsonArray.put(i, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonArray;
}
You have not added Items to singleorder.
You do it with a line like this:
singleorder.add(key, value);
Related
Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?
In my android i have got a response from Json but i want to get that Json value in Integer variable in android.In Jsonarray a i have got my value.So please help me for this. I have return that integer value in "MenuNameFromAndroid" function.
protected class AsyncMenuname extends
AsyncTask<MenunameSendFrom, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(MenunameSendFrom... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuNameFromAndroid(params[0].getMenuname());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject objects) {
try {
//JSONArray jsonArray = objects.getJSONArray("Value");
String string = null;
JSONArray a = objects.getJSONArray("Value");
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(TwoList.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
In this function i have got a response of JSON object
public JSONObject MenuNameFromAndroid(String getMenuname) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuNameFromAndroid");
p.put("getMenuname",mapObject(getMenuname));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
And This is function that I have return float value. That float value i want to get in android
float menuId = 0;
public float MenuNameFromAndroid(string getMenuname)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
menuId = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return menuId;
}
I have a WCF Webservice, in which send a data model and i get this in Android by JSon(By Entity Framework),any ways,
I can successfully get that JSON by this code and store all JSON Objects in JSONArray in the AsyncTas class, and in :
public class Consume extends AsyncTask<Void, Void, Void> {
InputStream inputStream = null;
String result = "";
private ArrayList<Contact> contacts = new ArrayList<Contact>();
#Override
protected Void doInBackground(Void... params) {
String URL = "http://x.x.x.x/MyWCF/Service1.svc/rest/getContact";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
//post.setHeader("content-type", "application/json");
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncoding", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("getContactResult"); //here i create the JsonArray of all JsonObjects
//Here is the solutions, We make a list of out Contact and make it as down
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(String.valueOf(jArray), listType);
//And here solution is ended !
} catch (JSONException e) {
e.printStackTrace();
}
}
And i created a Contact class in android, by this code :
public class Contact {
#SerializedName("name")
private String name;
#SerializedName("lastName")
private String lastName;
#SerializedName("phoneNumber")
private String phoneNumber;
#SerializedName("latitude")
private String latitude;
#SerializedName("longitude")
private String longitude;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLatitude() {
return latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLongitude() {
return longitude;
}
}
And i parse this JSONArray by Old ways !
By this method :
ArrayList<Contact> setFields(JSONArray jsonArray) {
ArrayList<Contact> contacts = new ArrayList<Contact>();
for(int i=0; i<jsonArray.length(); i++) {
try {
Contact contact = new Contact();
JSONObject object = (JSONObject) jsonArray.get(i);
contact.setName(object.getString("name"));
contact.setLastName(object.getString("lastName"));
contact.setPhoneNumber(object.getString("phoneNumber"));
contact.setLatitude(object.getString("latitude"));
contact.setLongitude(object.getString("longitude"));
contacts.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
return contacts;
}
It works, but I do not want to handle and parse JSONArray by this old way and wanna use GSON instead,any one can help me with this sample?
Here is my JSONArray and JSON Object :
{
"getContactResult": [
{
"id": 2041,
"lastName": "xxxx",
"latitude": xxx,
"longitude": xxx,
"name": "xxxx",
"phoneNumber": "xxxx"
}
]
}
Thx
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(jsonArray, listType);
This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java
This already answered but i want to share one thing for you.Easy and best way
There is one plugin Gson for android studio.You need to install.Then go to CTRL + insert.
You can create gson file.
Enter some name for java file.
Click that file then Paste you json data. Click ok.
You can see your created json to gson format.
thanks hope this will help you.
Kotlin Solution
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
val gson = Gson()
val type = object : TypeToken<List<Contact>>() {}.type
val listContact : KycProperties = gson.fromJson(jArray.toString(), type) as Contact
Java Solution
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> listContact;
Type type = new TypeToken<List<Contact>>() {
}.getType();
listContact= new Gson().fromJson(jsonArray.toString(), type);
Combining Gson and JSON (a different approach), Simple for newbies to understand. If your gson containing json array.
ArrayList<Sukh>sukhs new ArrayList<>();
Gson gson = new Gson();
try {
JSONArray jsonArray = new JSONArray(fullJsonArrayString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject=jsonArray.getJSONObject(i);
Sukh sukhObject = gson.fromJson(jsonObject.toString(), Sukh.class);
sukhs.add(sukhObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
here my jsonArray data like:
[{"LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00"},
{"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"}]
i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>() {
}.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
#Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}
}
/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return CompareString1.compareTo(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
I want to generate the following form
{
"dt": {
"DocumentElement": [
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "dfsfdsfd"
},
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "Chintan"
}
]
}
}
I have one arraylist which is dynamically filled with data and i also want the form in terms of dynamic. Here is my code:
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
}
DocumentElementobj.put( "DocumentElement", req );
System.out.println("Final "+DocumentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
It outputs:
Final {"DocumentElement":[]}
EDIT
Thanks to all your response. As per you all responce i make code like below
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObjdt = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", OnLineApplication.mParserResults.get(i).getCompanyId());
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
DocumentElementobj.put( "DocumentElement", req );
reqObjdt.put("dt", DocumentElementobj);
System.out.println("Final "+reqObjdt.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I get foramt which i want but in final string i get sequeence like below
{"dt":
{"DocumentElement":
[
{"Answer": "The Claims Representatives have a small role in return to work.","Question":"Return-to-Work Claim Issues. Please check the statement that best applies.","CompanyID":"8"},
{"Answer":"Poor","Question":"How would you describe the level of your general employee’s understanding of the impact of workers’ compensation costs on your organization?","CompanyID":"8"}]}}
it comes Answer first in sequence but i want to CompanyID first so what is issue in that?
You forgot to add JSONObject reqObj into JSONArray req. like req.put(reqObj);.
Modify your code block from for loop like
JSONObject reqObj = new JSONObject(); // Move inside the loop
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj); // ADDED HERE
You don't add the reqObj to req.
Do req.put(reqObj)
JSONObject documentElementobj = new JSONObject();
JSONArray req = new JSONArray();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
documentElementobj.put( "documentElement", req );
System.out.println("Final "+ documentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Also, it is better to make your variables begin with a lowercase letter, usually.
One more thing, using a debugger will be effective in this case.
There is a very good Google Libray called gson which help you to create Json Object or Parse Json Object with very ease.
You need to add gson.jar file in your project.
For More details go through the below link.
https://sites.google.com/site/gson/gson-user-guide
Edited Answer:-
public class DocumentElement {
#Expose
private String CompanyID;
#Expose
private String Question;
#Expose
private String Answer;
public DocumentElement(String CompanyID, String Question, String Answer) {
this.CompanyID = CompanyID;
this.Question = Question;
this.Answer = Answer;
}
public String getCompanyID() {
return CompanyID;
}
public String getQuestion() {
return Question;
}
public String getAnswer() {
return Answer;
}
}
public class Data {
#Expose
private ArrayList<DocumentElement> DocumentElement;
public ArrayList<DocumentElement> getDocumentElement() {
return DocumentElement;
}
public void setDocumentElement(ArrayList<DocumentElement> DocumentElement) {
this.DocumentElement = DocumentElement;
}
}
public class ParentData {
#Expose
private Data dt;
public Data getDt() {
return dt;
}
public void setDt(Data dt) {
this.dt = dt;
}
}
And used like this to create JsonObject by help of gson.jar
ArrayList<DocumentElement> doc=new ArrayList<DocumentElement>();
DocumentElement doc1=new DocumentElement("8", "Who I M?", "Amit");
DocumentElement doc2=new DocumentElement("9", "Who I M?", "Gupta");
doc.add(doc1);
doc.add(doc2);
Data data=new Data();
data.setDocumentElement(doc);
ParentData parent=new ParentData();
parent.setDt(data);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonObj = gson.toJson(parent);
System.out.println("createdJson:---"+jsonObj);
The Result are
{"dt":{"DocumentElement":[{"Answer":"Amit","CompanyID":"8","Question":"Who I M?"},{"Answer":"Gupta","CompanyID":"9","Question":"Who I M?"}]}}
Hope this will help you.
Use this code to fullfill your answer :
JSONObject jObj = new JSONObject("Your web Response");
JSONObject jObj1 = jObj.getJSONObject("dt");
JSONArray item = jObj.getJSONArray("DocumentElement");
for (int i = 0; i < item.length(); i++)
{
jObj_data = (JSONObject) item.get(i);
reqObj.put("CompanyID", jObj_data.getString("CompanyID"));
reqObj.put("Question",jObj_data.getString("Question"));
reqObj.put("Answer",jObj_data.getString("Answer"));
}