How to code this json in android - java

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.

Related

Handle array data from server android

in my application data coming from a server in the form of an array,
i cant handle the data i will share my code please help me.
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
s_key = jsonObject.getString("initKey");
s_iv = jsonObject.getString("initIv");
sec_url = jsonObject.getString("url");
s_init_hash = jsonObject.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
There is no JSONArray
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject .getJSONObject(i);
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
You Response is JSONObject not in JSONArray check it
FYI
{ } brackets means JSONObject
[ ] brackets means JSONArray
Parse your json like this
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
} catch (JSONException e) {
e.printStackTrace();
}
}
data Is not Json Array cause it start with {} it`s Json Object
Json Array start with []
So you need To use
SONObject jsonObjectData = jsonObject .getJSONObject(i);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
response
{
"status": "success",
"data": {
"initKey": "abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
Code
try {
JSONObject outerJsonObject=new JSONObject(response);
String status=outerJsonObject.getString("status");
if(status.equals("success"))
{
JSONObject innerJsonObjectData=outerJsonObject.getJSONObject("data");
String initKey =innerJsonObjectData.getString("initKey");
String initHash =innerJsonObjectData.getString("initHash");
String initIv =innerJsonObjectData.getString("initIv");
String versionNo =innerJsonObjectData.getString("versionNo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Comments
/*
{
//outerJsonObject
"status":"success",
"data": // innerJsonObjectData
{
"initKey":"abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
*/
When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example:
[{"name":"item 1"},{"name": "item2} ]
On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item. For example:
{"name": "item1", "description":"a JSON object"}
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject data = jsonObject. getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}

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

How to add JSONObject to Global JSONArray in another public class

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?

Android JSON object creation

How to create a JSON object, in Android using java code.
{
"apikey": "example apikey",
"id": "example id",
"email": {
"email": "example email",
"euid": "example euid",
"leid": "example leid"
}
}
You can create json you mentioned in question as below :
public void createJson() {
try {
// create outer json
JSONObject jsonObject = new JSONObject();
jsonObject.put("apikey", "example api key");
jsonObject.put("id", "example id");
// create email json
JSONObject emailJsonObject = new JSONObject();
emailJsonObject.put("email", "email");
emailJsonObject.put("euid", "euid");
emailJsonObject.put("leid", "leid");
// add email json to outer json
jsonObject.put("email", emailJsonObject);
System.out.println("-----printing json------" + jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks..!!
you can do like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("apikey","example apikey");
jsonObject.put("id","example id");
JSONObject innerObject = new JSONObject();
innerObject.put("email","example email");
....
jsonObject.put("email",innerObject);
and to convert to String you can do like jsonObject.toString();
Do like thist.
JSONObject myJson = new JSONObject();
myJson.put("apikey","example apikey");
myJson.put("id","example id");
JSONObject emailObject = new JSONObject();
emailObject.put("email","example email");
emailObject.put("euid","example euid");
emailObject.put("leid","example leid");
myJson.put("email",emailObject);
Create a class with the constructor you want.
Likes:
class MyJsonObj{
public string apikey;
public string id;
public string[] email;
}
Then instance the class
MyJsonObj myObj = new MyJsonObj();
myObj.apikey = "testKey";
myObj.id = "0123";
myObj.email = new string[]{"01#gamil.com","02#gmail.com"};
Last, convert to json string by Gson library
Gson gson = new Gson();
String json = gson.toJson(myObj);

Java Append object to JSON

I would like to append JSON object to existing JSON array to get data structure like this.
"results":[
{
"lat":"value",
"lon":"value"
},
{
"lat":"value",
"lon":"value"
}
]
I'm trying to do it using the code in example, but unfortunately whole object is overriden everytime.
Log.i(AppHelper.APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString);
AppHelper helper = new AppHelper(ctx);
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
//putv given values to the JSON
valuesObject.put("lat", lat.toString());
valuesObject.put("lon", lon.toString());
valuesObject.put("city", city);
valuesObject.put("street", street);
valuesObject.put("date", helper.getActualDateTime());
valuesObject.put("time", helper.getActualDateTime());
list.put(valuesObject);
//mainObject.put("values", list);
mainObject.accumulate("values", list);
saveJsonData(ctx, mainObject.toString(),"positions");
How it should be right?
Put and accumulate everytime rewrite all previous values, but i would like to append this object:
{
"lat":"value",
"lon":"value"
},
Into results parent.
BTW: I would like to do it without GSON.
Thanks for any help..
There isnt any problem with your code. It does append
String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);
This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}.
Isnt this what you are expecting?
With gson you can do like
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class AddJson {
public static void main(String[] args) {
String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
Gson gson = new Gson();
JsonObject inputObj = gson.fromJson(json, JsonObject.class);
JsonObject newObject = new JsonObject() ;
newObject.addProperty("lat", "newValue");
newObject.addProperty("lon", "newValue");
inputObj.get("results").getAsJsonArray().add(newObject);
System.out.println(inputObj);
}
}
Simple Approach
String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
System.out.println(jsonData);
try {
JSONArray result = new JSONObject(jsonData).getJSONArray("results");
result.getJSONObject(0).put("city","Singapore");
jsonData = "{\"results\":"+result.toString()+"}";
System.out.println(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
OutPut Before Appending
{"results":[{"lat":"value","lon":"value" }]}
OutPut After Appending
{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}
If you want to add new value to an Object you can try the below as well
Before:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty"
}
code :
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(TheObjectToWhichYouWantToAddNewValue);
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.putPOJO("new Key","new value")
after:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty",
"new Key": "new value"
}

Categories

Resources