How to process a JSON with multiple array s - android

The is my JSON string .
{
"server_response":
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
}
I think there would be a '[' after "server_response" , but not sure .
I am trying to retrieve the data but the code is not working .
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count=0 ;
String stoppage,busno;
while(count<1)
{
JSONArray JA = jsonArray.getJSONArray(0);
JSONObject JO = JA.getJSONObject(count);
stoppage = JO.getString("stoppage_name");
busno = JO.getString("bus_no");
Toast.makeText(getApplicationContext(),"Stoppage ="+ stoppage+" Bus no =" +busno, Toast.LENGTH_LONG).show();
count ++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Where I am making wrong . I am new to JSON and Android.

jsonObject = new JSONObject(json_string);
jsonServerObject = jsonObject.getJSONObject("server_response");
jsonSourceArray = jsonServerObject.getJSONArray("source_response");
jsonDestinationArray = jsonServerObject.getJSONArray("destination_response");
//Iterate your 2 arrays

server_response is not a JSONArray, it's a JSONObject. Because array have numeric key, not string.

i have already answer this type of question .. what you have to do .. use multiple for loop to getting value inside array under array.
this is srceen shots
JSONArray objJson = new JSONArray(strJSONData);
System.out.println("AppUserLogin:"+objJson);
// Parsing json
if(arrJson.length()>0)
{
for (int i = 0; i < objJson.length(); i++) {
try {
JSONObject objprod = arrJson.getJSONObject(i);
HashMap<String, String> MaplistTemp = new HashMap<String, String>();
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
JSONArray objproduct_var = new JSONArray(objprod.getString("LearningStandards"));
if ((objproduct_var.length()) > 0) {
for (int k = 0; k < objproduct_var.length(); k++) {
JSONObject objprodvar = objproduct_var
.getJSONObject(k);
MaplistTemp
.put("1",
objprodvar
.getString("1"));
MaplistTemp
.put("2",
objprodvar
.getString("2"));
MaplistTemp
.put("3",
objprodvar
.getString("3"));
MaplistTemp
.put("4",
objprodvar
.getString("4"));
}
}
// sub_categorys_details.add(sub_cat_det);
medpostList.add(MaplistTemp);// adding to final hashmap
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Try this , and {} = object [] = array
try{
jsonObject = new JSONObject(json_string);
injsonObject = jsonObject.getJSONObject("server_response");
jsonArray = injsonObject.getJSONArray("source_reponse");
}catch(Exception e){}

sonArray = jsonObject.getJSONArray("server_response");
Here you are trying to access server_response as an array. It isn't an array. "server_response" is the key to the nested object:
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
See? Thats not an array, tis a JSON object with two keys, each of them have an array as value.
I'm not very familiar with android or java but in plain old javascript you could try something like:
var sourceResp = jsonObject.server_response.source_response;
or
var sourceResp = jsonObject["server_response"]["source_response"];
That will produce an array with one item in it.
I hope this can get you going.

Related

How can I parse a json with colon in android?

I have a json with colon between the strings, and I'm not sure how can I parse it. I know that I don't have an array in the json, but I'm not sure how can I get the values...
{
"config": {
"network": {
"hni:21407" : "num:[INTNUM]",
"hni:311490" : "num:044[INTNUM]"
}
}
}
This is what I'm trying, but I never go through the loop for, and not really sure if I need it.
JSONObject obj = new JSONObject(netWorkJson);
String arr = obj.optString("network");
for(int i = 0; i < arr.length(); i++) {
String hni = obj.getString("hni");
String num = obj.getString("num");
}
Thanks in advance
You first need to parse the inner json object "network", after that you can loop over it's keys and get the values for them one by one:
private void parseJSON(String netWorkJson) throws JSONException {
JSONObject obj = new JSONObject(netWorkJson);
JSONObject config = obj.getJSONObject("config");
JSONObject network = config.getJSONObject("network");
Iterator<?> keys = network.keys();
while(keys.hasNext()) {
String key = (String) keys.next();
String value = network.getString(key);
}
}
Beauty of this is that it will also work if you had 100 hni values for example, and that you don't have to get them one by one.
network is JSONObject instead of JSONArray, so no need to use for-loop for getting value from it.just use do it as:
JSONObject obj = new JSONObject(netWorkJson);
// get network JSONObject from obj
JSONObject network=obj.getJSONObject("network");
// get both values from network object
String strHni=network.optString("hni:21407");
String strNum =network.optString("hni:311490");
JSONObject message = new JSONObject(config);
String value=message.getJSONObject("network").getString("hni:21407")
Try This
try {
JSONObject jsonObject = new JSONObject("config");
JSONArray jsonArray = jsonObject.getJSONArray("network");
for(int i =0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String hni21407 = jsonObject1.getString("hni:21407");
String hni311490 = jsonObject1.getString("hni:311490");
}
} catch (JSONException e) {
e.printStackTrace();
}

How to create JSONObject and JSON ARRAy from json string in android?

My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}

Unable to get the JSON data from the JSONObject in android?

Currently, I'm having a minor trouble trying to get the string data from the jsonArray, however, I'm unable to get the value . I've got the data in the json object Example:
{
"lot":[
{
"id":"271",
"lot_date":"2015-05-25"
}
],
"numb3":[
{
"id":"675",
"lot_date":"2015-05-25"
}
],
"num4":[
{
"id":"676",
"lot_date":"2015-05-25"
}
],
"result":"OK"
}
The data above is stored in the JsonObject jsonobj. And what I want to do is to check if the JSON array JSONArray lot6 = jsonobj.optJSONArray("lot6"); contains the values or not , and if it's not null get the string data. However, even the data contains in the lot6 array, the result is null.
JSONArray lot6 = jsonobject.optJSONArray("lot6");
Log.d("LOT6",lot6+"");
if (lot6 != null) {
jsonarry2 = jsonobject.getJSONArray("lot6");
//3.if not null get the string data from the
for (int i = 0; i < jsonarry2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarry2.getJSONObject(i);
ListData worldpop = new ListData();
worldpop.set_date(jsonobject.optString("lot_date"));
worldpop.set__id(jsonobject.optString("id"));
world.add(worldpop);
}
//5. test this part of the variable
String lotdate = world.get(0).get_date();
String lotid = world.get(0).get__id();
Hi please check Not lot6 its lot. please folloe below formate to get out out.
String s="{\"lot\":[{\"id\":\"271\",\"lot_date\":\"2015-05-25\"}],\"numb3\":[{\"id\":\"675\",\"lot_date\":\"2015-05-25\"}],\"num4\":[{\"id\":\"676\",\"lot_date\":\"2015-05-25\"}],\"result\":\"OK\"} ";
try{
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
String arr[]={"lot","numb3","num4"};
for(int i=0;i<json.size()-1;i++){
JSONArray ja=(JSONArray)json.get(arr[i]);
for(int j=0;j<ja.size();j++){
JSONObject jo1=(JSONObject) ja.get(j);
System.out.println("lot_date: "+jo1.get("lot_date")+" Id "+jo1.get("id"));
}
// System.out.println(ja);
}
System.out.println(json.get("result"));
}catch (Exception e) {
System.out.println(e);
}

getting JSONArray at Index from JSONObject

I have a JSONObject with multiple JSONArrays in it. I have written a for loop to loop through the object but i need to get the JSONArray at the Index position. Does anyone know how to do this?
heres my JSONObject
{"Contacts": //JSONObject
{
"B"://JSONArray..
[
{"ContactName":sdfsdf,"ID":900,"Number":1368349},
{"ContactName":adsdfd,"ID":1900,"Number":136856},
{"ContactName":adglkhdofg,"ID":600,"Number":136845}
],
"C":[
{"ContactName":alkghoi,"ID":900,"Number":1368349},
{"ContactName":wetete,"ID":1900,"Number":136856},
{"ContactName":dfhtfh,"ID":600,"Number":136845}
]
.....//and so on..
}
}
heres my for loop this issue i'm having is that to retrieve a JSONArray from a JSONObject it requires a string but i'm trying to get the Array at object Index in the JSONObject
JSONArray headerStrings = contacts.names();
Log.v("Main", "headerStrings = " + headerStrings);
SeparatedListAdapter adapter = new SeparatedListAdapter(this);
for (int t=0; t<contacts.length(); t++){
adapter.addSection(headerStrings.getString(t), new DocumentArrayAdapter (getActivity(),R.layout.document_cell,contacts.getJSONArray(t););
}
Try this:
for (Iterator it = contacts.keys(); it.hasNext(); ) {
String name = (String)it.next();
JSONArray arr = contacts.optJSONArray(name);
// now add this to your adapter
}
Note, that the order of the elements of a JSONObject is not defined.
Here, You will get matched index.
int matchedIndex =0;
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if( 123 == jsonObject.getInt("Id")){
matchedIndex = i;
//jsonArraySelectedBikes.remove(matchedIndex);
break;
}
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources