How to get single object value and send to server - android

I have the following JSON response i want to get separate values like CHIL SEZ IT Park,Coimbatore,Tamil Nadu,India
JSON String is:
[
{
"value": "CHIL SEZ IT Park",
"offset": 0
},
{
"value": "Coimbatore",
"offset": 18
},
{
"value": "Tamil Nadu",
"offset": 30
},
{
"value": "India",
"offset": 42
}
]

Try this:
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(responseStr);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String value = jsonObject.getString("value");
arrayList.add(value);
}
} catch (JSONException e) {
e.printStackTrace();
}

Place this function and pass the jsonString. You will get the ArrayList from the JSON.
public ArrayList<String> getPlaceName(String jsonString){
ArrayList<String> places = new ArrayList<>();
try{
JSONArray array = new JSONArray(jsonString);
for(int x=0;x<array.length();x++){
places.add(array.getJSONObject(x).getString("value"));
}
}catch (JSONException e){}
return places;
}

Related

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

Parsing json (android) [duplicate]

Before I parse json json array, but this json object. Its It drove me to a standstill. How i can parse json like this:
{ "test1": {
"1": {
"action": "0",
"type": "1",
"id": "1",
},
"2": {
"action": "0",
"type": "1",
"id": "2",
}
},
"test2": {
"1": {
"id": "1",
"name": "one"
},
"2": {
"id": "2",
"name": "two"
},
"5": {
"id": "5",
"name": "three"
}
}}
When you don't have a fixed set of keys, that you know upfront, the only way to parse it is to use keys(). It returns an Iterator with the keys contained in the JSONObject. In your case you could have
JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
JSONObject obj = jsonObject.optJSONObject(key);
if (obj != null) {
Iterator<String> iterator2 = obj.keys();
}
}
iterator will return test1 and test2, while iterator2 will return 1 and 2, for test1 and 1 ,2 , 5 for test2
You can create a JSONObject From string as bellow
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
and to parse the jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
to get String values
String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);
if need them as JSONArray the you can try
public JSONArray getJsonArray (JSONObject jsonObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < nameJsonArray.length(); i++) {
try {
String key = nameJsonArray.getString(i);
jsonArray.put(jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}
in case keys like test1,test2,test3...
JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
JSONArray jsonArray = new JSONArray();
for (int i = 1; i <= jsonObject.names().length(); i++) {
try{
jsonArray.put(jsonObject.getString("test" + i));
}catch (JSONException e){
e.printStackTrace();
}
you can get your JSONArray this way.

How to select only particular values from bunch of JSON response?

I want to get only some selected values from the JSON response.For example if JSON contains 100 string values then i need to take the values which are starting with # symbol from that 100 values.
How can I do that ?
Following is my JSON,
[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
}]
Here I need to fetch Name which having # symbol
You can use below method to get the Name which start with # :
JSONObject jsonObject = new JSONObject(response);// u can change it as per your need
JSONArray jArray = jsonObject.getJSONArray("Obj");// if your `Obj` is an JsonArray
for (int i = 0; i < jArray.length(); i++) {
String json_name = jArray.getJSONObject(i).getString("NAME");
if(json_name.startsWith("#"))
{
Log.d(TAG,"It start with #");
}
}
Try out as below:
private void parseJSON(String json) {
try {
JSONArray items = new JSONArray(<your Json Response>);
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
System.err.println("Object---" + item.getString("Obj"));
JSONObject obj=item.getJSONObject("Obj");
for (int j = 0; j < obj.length(); j++) {
String Name=obj.getString("NAME");
if(obj.getString("NAME").toString().contains("#"))
{
Log.d("Name starts with-->", Name);
}
else
{
Log.d("Name does not start with-->", Name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try this.
first of all that's not a valid json may be below json is correct format
[
{
"Obj": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
}
]
}
]
if your response like above try below code this may help you.
try {
JSONArray jsoArray = new JSONArray(json);
JSONArray JobjArray = jsoArray.getJSONObject(0).getJSONArray("Obj");
for(int i=0; i < JobjArray.length(); i++)
{
JSONObject Jobj = JobjArray.getJSONObject(i);
Iterator<String> iter = Jobj.keys();
while (iter.hasNext()) {
String key = iter.next();
Log.v("key--", key);
try {
Object value = Jobj.get(key);
Log.v("value--", ""+value);
String str_value = value.toString().trim();
if(str_value.startsWith("#"))
{
Log.d(""+str_value,"value started with #");
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Parsing string to json on android

How to parse HTTP response ton JSON object ?
I changed my json code to:
{
"data": [{
"id": 1,
"sensor1": 76,
"sensor2": 75
}, {
"id": 2,
"sensor1": 76,
"sensor2": 206
}]
}
And my code is now:
JSONObject json = new JSONObject(mJson);
try {
data = json.getJSONArray("data");
for (int i = 0; i < json.length(); i++) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
JSONObject obj = (JSONObject) data.get(i);
map.put(TAG_SENSOR_1, obj.getInt("sensor1"));
map.put(TAG_SENSOR_2, obj.getInt("sensor2"));
dataList.add(data.getInt("id") - 1, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
But I have the same problem
edit your string to this format
{content:[{
first:1,
second:76,
third:75
},
{
first:2,
second:76,
third:75
},
{
first:3,
second:206,
third:75
},
{
first:4,
second:6,
third:175
},
{
first:5,
second:176,
third:75
}]
}
then use JSONObject and JSONArray to convert string
JSONArray array = new JSONObject(string).getJSONArray("content");
for(int i=0;i<array.size();i++){
JSONObject obj = array.get(i);
Log.i(TAG,"obj.getInt = "+obj.getInt("first"));
Log.i(TAG,"obj.getInt = "+obj.getInt("second"));
Log.i(TAG,"obj.getInt = "+obj.getInt("third"));
}

Nested JSON arrays

I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?
You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck
Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");

Categories

Resources