Android - Reading an array from intent and adding it to JsonObject - android

In one of my libraries say libA, I am reading a JsonArray (with string values in it) from JsonObject and converting it to String[] before adding it to an intent as extra and then I pass down that intent to another activity say activityA. I am reading from intent in activityA and creating a JsonObject out of it for use later, but am not able to add an array directly to a JsonObject.
Code in libA:
JsonObject metadata; // This has the JsonArray in it.
final String[] bookIdsArray = new Gson().fromJson(metadata.get("bookIds") , String[].class);
testIntent.putExtra("bookIds", bookIdsArray);
Code in activityA:
final JsonObject activityMetadata = new JsonObject();
activityMetadata.addProperty("bookIds", String.valueOf(intent.getStringArrayExtra("bookIds")));
addProperty method of JsonObject only accepts String, Number, Boolean or Character and another method called 'add' only accepts JsonElement. How can I directly add array to it?

Use the JsonObject method add(String property, JsonElement value) as JsonArray extends JsonElement.
String[] idsFromIntent = intent.getStringArrayExtra("bookIds");
JsonArray bookIds = new JsonArray();
for (String id : idsFromIntent) {
bookIds.add(id);
}
activityMetadata.add("bookIds", bookIds);

Related

Unable to get JSON data in Android

I want to send a JSON list from one activity to other. I am doing in this way
For sending
List<JSONObject> jsonList = new ArrayList<JSONObject>();
Intent i = new Intent(getApplicationContext(), AdapterContent.class);
Bundle b = new Bundle();
b.putString("Array",jsonList.toString());
i.putExtras(b);
For receiving
Bundle b = getIntent().getExtras();
String Array=b.getString("Array");
Log.i("TAG" ,Array);
JSONObject jsonobj = new JSONObject(Array);
Log.i("Name" , String.valueOf(jsonobj.getString("Name")));
JSON Object
[
{"Name":"Area1"},
{"Name":"Area 2"}
]
But it is prompting
W/System.err:at com.example.data.mydata.onCreate
It is printing the Array but not the Name from JsonObj
Is anything wrong here?
// make a json array
JSONArray jsonArr = new JSONArray(Array);
// empty containers for later use
JSONObject jobj;
String name=null;
// traverse all json object according to index of jsonarray
for(int i=0;i<jsonArr.length();i++){
// fetch jasonObject according to index
jobj=jsonArr.getJSONObject(i);
// get the name string from object and use it accordingly
name=jobj.optString("Name");
}
you must cast the json string into json array not as json object
String Array = getIntent().getExtras().getString("Array");
Log.i("TAG" ,Array);
JSONArray jsonArr = new JSONArray(Array);
JSONObject jsonObj;
for(int i=0;i<jsonArr.length();i++){
jsonObj = jsonArr.getJSONObject(i);
Log.i("Name" , String.valueOf(jsonObj.getString("Name")));
}
Note: it is recommended to serialize or convert the data to parcelable while passing between activities
Why do you need to send JsonList . It's better to create a model class for your List. and make it parcelable. and send it to another activity
intent.putExtra(Key,yourModelClass);

Convert JSONObject into String array

I'm receiving a JSONObject like this
{"tag":"value1", "tag":"value2", .............}
How do I make it into a String array of
["value1", "value2"]
Create the Arraylist and get the string from the jsonobject and stored it in the arraylist.
Do like this
ArrayList tagarray=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
tagarray.add(jo.getString("tag"));
}
Try this way
JSONObject obj = new JSONObject("");
Iterator<String> itr = obj.keys();
int i=0;
String[] values = new String[obj.length()];
while(itr.hasNext()){
values[i++] = obj.getString((String)itr.next());
}
Use following code.
ArrayList array=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
array.add(jo.getString("tag"));
}
String[] Arr = new String[array.size()];
Arr = array.toArray(Arr);
Or you have another option.
JSONObject jo=new JSONObject(jsonstring);
String[] array = new String[jo.length()];
for(int i=0;i<jo.length();i++){
array[i] = jo.getString("tag");
}
There is super cool , lib called GSON , which is really helpfull for converting all type of JSON into its object .
If tags are going to be tag1, tag2 and so on...you can use a for loop,
string[i] = jsonObj.getString("tag"+i);
Or you can make a model class with datatype of String or ArrayList tag , eg.
class ModelClass{
ArrayList<String> tag;
//getter setter here
}
And with that use Gson for JSON parsing and mapping the data,
Gson gson = new Gson();
modelClass= gson.fromJson(yourJson,ModelClass.class);
And your work is done. You have each value in the ArrayList tag.
This is more useful for parsing and mapping long and-or complex json strings.
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like #SerializedName. (So no need to use Serializable)

How to parse a compact JSON Array in android

I have a JSON Array like this:
[4, 3, 2, 1,...]
It is a simple array, and I am not able to find a single tutorial that tells me how to parse this array. I want to assign each element to a string Array that I have created like:
String H[];
I always get stuck when it comes to returning a value from a method, I get confused. For Example:
Within the Oncreate() method, after initializing all variables I type:
solarData();
//displaying only one value from the String Array H[];
TextView.setText(H[0]);
public JSONArray solarData() throws JSONException{
//After getting response from HttpClient and getting result
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray,length();i++){
String H[i] = jArray.getJSONObject(i).toString();
}
return jArray;
}
Now what is it returning? I want it to return the String Array. So that I can display any value I want from the String Array to which I am storing these values.
From the JSONArray documentation, you can see there is a constructor that takes a valid JSON string and does all of the parsing work for you. You seem to have identified this already.
The problem here is that in each iteration of your for loop, you are attempting to create a new String array. You should initialize your array before the loop, and then populate its contents after initializing it. Something like this should work for you:
public JSONArray solarData() throws JSONException{
JSONArray jArray = new JSONArray(result);
// consider renaming H to something meaningful (e.g. planetList)
String H[] = new String[jArray.length()];
for (int i=0; i < jArray,length() ;i++) {
H[i] = jArray.getJSONObject(i).toString();
}
return jArray;
}

Simple Json parsing in android

I got the Json response. I am not able to get the values from the string.my string is
Json_response is
{"NameAllList":[{"Current":{"time":"2012-02-21T08:04:21","Name":"abcd"},
"Next":{"Name":"data1","StartTime":"2012-02-21T08:06:21"}},{"Current":{"time":"2012-02-21T08:14:21","Name":"defg"},
"Next":{"Name":"data2","StartTime":"2012-02-21T08:24:21"}},{"Current":{"time":"2012-02-21T08:28:21","Name":"ghij"},
"Next":{"Name":"data3","StartTime":"2012-02-21T08:34:21"}},{"Current":{"time":"2012-02-21T08:40:21","Name":"knmo"},
"Next":{"Name":"data4","StartTime":"2012-02-21T08:48:21"}}]}
and i tried this.
JSONObject jsonObj = new JSONObject(json_response);
JSONObject subObj = jsonObj.getJSONObject("Current");
String name_current =subObj.getString("Name");
but i am not able to get the value of "Name". what mistake i have done. provide the link to do the above parsing.
first of all, your JSON response is having NameAllList as a JSON Array of objects.
So you have to fetch JSON Array first, then you can fetch one-by-one object.
for example:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
for(int i=0; i<array.length(); i++)
{
// Retrieve Current object as such
JSONObject objCurrent = array.getJSONObject("Current");
// Retrieve Next object as such
JSONObject objNext = array.getJSONObject("Next");
}
You are not parsing json properly, so you are not able to fetch value of Name. Please note JSON Annotation [] represent JSONArray, and {} respresent JSONObject, so method to get current item's name is:
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArr=jsonObj.getJSONArray("NameAllList");
String Hora_name_current="";
for(int i=0;i<jsonArr.length();i++)
{
JSONObject obj=jsonArr.get(i);
try{
JSONObject subObj = obj.getJSONObject("Current");
Hora_name_current =subObj.getString("Name");
break;
}catch(JSONException ex)
{
}
}
looks like you're trying to use JSONObject when you should be using JSONArray for the second request. Try this:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
In your JSON return, "NameAllList is actually an array and needs to be handled as such. Once you set it to "array", you can then run a for loop and treat it like any other array in Java.
Let me know if that helps.
David
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArray = jsonObj.getJSONArrays("NameAllList");

Removing Object from JSONArray

I have an application that gets an api key and account name from a webservice, I am storing this apikey and account name for further use(multiple accounts and apikeys).
because you can only store primitive types in the sharedPreferences I parse the JSONArray toString.
In another part of the application the user must be able to remove an account from his app.
So I retrieve the string and Parse it back to an JSONArray.
how do I remove an JSONObject from the array and save it so I can parse it back to an string and save it again?
You should convert it in arraylist and remove object and create jsonarray,,,
ArrayList<String> list = new ArrayList<String>();
//First Position remove
list.remove(0);
JSONArray jsArray = new JSONArray(list);
i use:
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}

Categories

Resources