How to add JSONObject to Global JSONArray in another public class - java

I have a problem or maybe better a dilemma. I must add a JSONObject to Global JSONArray that I later get this array from another activity. What is a better solution?
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("strefa", strefa);
jsonObject.put("adres", adres);
jsonObject.put("kryteria", kryteria);
jsonObject.put("telefon", telefon);
jsonObject.put("data", data);
} catch (Exception e) {
e.printStackTrace();
}
GlobalConfig.JsonArray.put(jsonObject); // this is public static JSONArray JsonArray = new JSONArray();
or better is create a public method with a private object in GlobalConfig class?

Related

How to code this json in android

hi I am new in this forum I am trying the following in Android studio, I need to create a json object with this format
{
"enviaya_account": "Y0DCRGIU",
"carrier_account": null,
"api_key":"YOUR_API_KEY",
"shipment":{
"shipment_type":"Package",
"parcels":[
{
"quantity":"1",
"weight":"3",
"weight_unit":"kg",
"length":"10",
"height":"20",
"width":"30",
"dimension_unit":"cm"
}
]
},
"origin_direction":{
"country_code":"MX",
"postal_code":"11550"
},
"destination_direction":{
"country_code":"MX",
"postal_code":"01210"
},
"insured_value":"5000",
}
"insured_value_currency":"MXN"
}
but I can not integrate it well since it marks me errors could someone help me please? the code that I have is this:
JSONObject Request = new JSONObject();
JSONObject shipment = new JSONObject();
JSONArray parcels = new JSONArray();
JSONObject parcel= new JSONObject();
JSONObject origin_direction = new JSONObject();
JSONObject destination_direction = new JSONObject();
try {
Request.put("enviaya_account","Y0DCRGIU");
Request.put("carrier_account","");
Request.put("api_key","xxxxxxxxxxxxxxxxxxxxxxxxxxx");
shipment.put("shipment_type","package");
Request.put("shipment",shipment);
parcel.put("quantity","1");
parcel.put("weight","10.98");
parcel.put("weight_unit","kg");
parcel.put("length","39");
parcel.put("height","39");
parcel.put("width","29");
parcel.put("dimension_unit","cm");
parcels.put(parcel);
Request.put("parcels",parcels);
origin_direction.put("country_code","MX");
origin_direction.put("postal_code","29267");
destination_direction.put("country_code","MX");
destination_direction.put("postal_code","34200");
Request.put("origin_direction",origin_direction);
Request.put("destination_direction",destination_direction);
Request.put("insured_value","0");
Request.put("insured_value_currency","MXN");
} catch (JSONException e) {
e.printStackTrace();
}
edt.setText(Request.toString());
but when I try to check it in POSTMAN it tells me that the parcels object does not exist
As far as I know since "parcels" is defined as a JSONArray object, you need to call add method.
parcels.put(parcel);
// should instead be
parcels.add(parcel);
I have changed your code of some part.
JSONObject Request = new JSONObject();
JSONObject shipment = new JSONObject();
JSONArray parcels = new JSONArray();
JSONObject parcel= new JSONObject();
JSONObject origin_direction = new JSONObject();
JSONObject destination_direction = new JSONObject();
try {
Request.put("enviaya_account","Y0DCRGIU");
Request.put("carrier_account","");
Request.put("api_key","xxxxxxxxxxxxxxxxxxxxxxxxxxx");
shipment.put("shipment_type","package");
parcel.put("quantity","1");
parcel.put("weight","10.98");
parcel.put("weight_unit","kg");
parcel.put("length","39");
parcel.put("height","39");
parcel.put("width","29");
parcel.put("dimension_unit","cm");
parcels.put(parcel);
shipment.put("parcels",parcels);
Request.put("shipment",shipment);
origin_direction.put("country_code","MX");
origin_direction.put("postal_code","29267");
destination_direction.put("country_code","MX");
destination_direction.put("postal_code","34200");
Request.put("origin_direction",origin_direction);
Request.put("destination_direction",destination_direction);
Request.put("insured_value","0");
Request.put("insured_value_currency","MXN");
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("Json value", String.valueOf(Request));
this give me result like below screen shot.

Java : How to extend a class and use a dot notation on its object

Take for example the class JSONObject.
And say I have the following method.
public JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
How do I extend the JSONObject so that I'll end up with a method like.
JSONObject man = new JSONObject("name");
man.getObjectOrThrow("name");
Where "name" is the key to the child node of "man".
Also for reference, what is this called?
Custom Class
public class CustomJSONObjectProvider extends JSONObject {
public JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
// all the other custom methods that you want to override
}
And the way you use it
CustomJSONObjectProvider customJSONObjectProvider = new CustomJSONObjectProvider();
JSONObject jsonObject = customJSONObjectProvider.getObjectOrThrow("name");
It can also be static
public class CustomJSONObjectProvider extends JSONObject {
public static JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
// all the other custom methods that you want to override
}
Its usage
JSONObject jsonObject = CustomJSONObjectProvider.getObjectOrThrow("name");

Android org.json.jsonarray cannot be converted to jsonobject error

I'm new in JSON, but I try to use all answers and didn't work. Help please, what I doing wrong.
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
editText.setText(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray resultArray = jsonObject.getJSONArray("query");
addresses = new ArrayList<String>();
for (int i = 0; i<resultArray.length(); i++){
addresses.add(resultArray.getJSONObject(i).getString("Name"));
Log.d("DTA",resultArray.getJSONObject(i).getString("Name"));
}
refreshAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
It's my JSON for parsing.
{
"query":{
"count":2,
"created":"2016-10-04T19:50:08Z",
"lang":"ru",
"results":{
"rate":[
{
"id":"USDRUB",
"Name":"USD/RUB",
"Rate":"62.8240",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"62.8416",
"Bid":"62.8240"
},
{
"id":"EURRUB",
"Name":"EUR/RUB",
"Rate":"70.3460",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"70.3740",
"Bid":"70.3460"
}
]
}
}
}
That's because query is not an array, it is an object. I guess you want to get the objects from rate, this is how to do it:
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject resultsObject = jsonObject.getJSONObject("results");
JSONArray resultArray = resultsObject.getJSONArray("rate");
... etc... now iterate

Parsing JSON to custom ArrayList, only returning last item?

I'm finding this a bit odd, I'm parsing some JSON from a file in my /assets folder. I have set up a custom ArrayList. Now when I try and add data from the ArrayList to a listview, or a spinner (Same adapter) it only shows the last item. Here is my code:
My parsing method:
public ArrayList<ShopName> parseJSON(String json) {
ArrayList<ShopName> shop = new ArrayList<>();
ShopName item = new ShopName();
Log.d(TAG, json);
try {
JSONArray jArray = new JSONArray(json);
for (int i=0; i < jArray.length();i++) {
JSONObject jObject = jArray.getJSONObject(i);
item.setFromCurrency(jObject.getString("from"));
item.setToCurrency(jObject.getString("to"));
item.setRate(jObject.getString("cost"));
data.add(item);
}
} catch (JSONException jen) {
jen.printStackTrace();
}
return shop;
}
I'm not quite sure where my error is. Am I parsing it incorrectly, maybe, storing it incorrectly? I have a feeling it's my ArrayList but I'm sure what I should be doing to fix it, I've tried using different Adapters, and searching StackOverflow but they all have difference issues so it's hard to narrow now.
I would appreciate your help on this. Thank you.
public ArrayList<Data> parseJSON(String json) {
ArrayList<Data> data = new ArrayList<>();
// Data item = new Data(); // Move this into for loop
Log.d(TAG, json);
try {
JSONArray jArray = new JSONArray(json);
for (int i=0; i < jArray.length();i++) {
Data item = new Data();
JSONObject jObject = jArray.getJSONObject(i);
item.setFromCurrency(jObject.getString("from"));
item.setToCurrency(jObject.getString("to:"));
item.setRate(jObject.getString("rate"));
data.add(item);
}
} catch (JSONException je) {
Log.d(TAG, je.getMessage());
}
return data;
}
You only initialize item object once, that's why. Move
Data item = new Data();
Into your for loop.
You should create new Data object for each JSON array item.
public ArrayList<Data> parseJSON(String json) {
// remove this
// Data item = new Data();
...
try {
JSONArray jArray = new JSONArray(json);
for (int i=0; i < jArray.length();i++) {
// move it here
Data item = new Data();
...
data.add(item);
}
} catch (JSONException je) {
Log.d(TAG, je.getMessage());
}
return data;
}

Creating a JSON object

I am making a JSON request to server using Java. Here is the following parameters.
{method:'SearchBySearchConfiguration',params:[{{SearchCriteria:'%arriva',
IsAccountSearch:true,IsContactSearch:false,SearchByName:true,SearchByAddress:false
CRMTextValues:[], CRMCurrencyValues:[]}]}
I could do this way.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
How do I add the rest of params, in name-value pair to JSON object?
Thanks in advance!
One way I can think of is using the org.json library. I wrote a sample to build part of your request object:
public static void main(String[] args) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "SearchBySearchConfiguration");
JSONArray jsonArray = new JSONArray();
JSONObject innerRecord = new JSONObject();
innerRecord.put("SearchCriteria", "%arriva");
innerRecord.put("IsAccountSearch", true);
jsonArray.put(innerRecord);
jsonObject.put("params",jsonArray);
System.out.println("jsonObject :"+jsonObject);
}
The output is :
jsonObject :{"method":"SearchBySearchConfiguration","params":[{"IsAccountSearch":true,"SearchCriteria":"%arriva"}]}
Another technique would be to build Java objects that resemble your request structure. You can then convert it into json using Jackson library's ObjectMapper class.
In both cases once you get the json string, you can directly write it into the request body.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
JSONArray paramsArr = new JSONArray();
JSONObject arrobj = new JSONOject();
arrobj.put("SearchCriteria","%arriva");
arrobj.put("IsAccountSearch","true");
arrobj.put("IsContactSearch","false");
arrobj.put("SearchByName","true");
arrobj.put("SearchByAddress","false");
arrobj.put("CRMTextValues",new JSONArray());
arrobj.put("CRMCurrencyValues",new JSONArray());
paramsArr.put(arrobj);
json.put("params",paramsArr);
The you can create JSONArray and put that array in JSONObject
Its Better to use gson for this.
First you need to create classs with following members :
public class TestClass{
private String method;
private ParamClass params;
}
public class ParamClass{
private String SearchCriteria;
private boolean IsAccountSearch;
private boolean IsContactSearch;
private boolean SearchByName;
private boolean SearchByAddress;
private String[] CRMTextValues;
private String[] CRMCurrencyValues;
}
Usage :
Serializing :
Gson gson = new Gson();
String jsonString = gson.toJson(testClassObject);
Deserializing :
Gson gson = new Gson();
TestClass testClassObject = gson.fromJson(jsonString , TestClass.class);
See this below example, where a JSONArray is returned and then how i am converting it in JSONObject form...
public JSONArray go() throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx");
return json;
}
JSONArray jarr;
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){}
Jackson is a very efficient to do JSON Parsing
See this link:
http://jackson.codehaus.org/
Gson is provided by google which is also a good way to handle JSON.
To add params, JSONArray is used.
Inside params, we use JSONObject to add data such as SearchByAddress, IsAccountSearch ..etc.
Reference http://www.mkyong.com/java/json-simple-example-read-and-write-json/
package com.test.json;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("method", "SearchBySearchConfiguration");
JSONArray list = new JSONArray();
JSONObject innerObj = new JSONObject();
innerObj.put("SearchCriteria","%arriva" );
innerObj.put("IsAccountSearch",true);
innerObj.put("IsContactSearch",false);
innerObj.put("SearchByName",true);
innerObj.put("SearchByAddress",false);
innerObj.put("CRMTextValues",new JSONArray());
innerObj.put("CRMCurrencyValues",new JSONArray());
list.add(innerObj);
obj.put("params", list);
System.out.print(obj);
}
}

Categories

Resources