I converted an ArrayList to an JSONArray. How can I convert it back?
The final result must be an ArrayList. Thank you in advance.
EDIT:
This is how I convert the ArrayList to JSONArray:
String string_object= new Gson().toJson(MyArrayList<OBJECT>);
JSONArray myjsonarray = new JSONArray(string_object);
You can convert your JsonArray or json string to ArrayList<OBJECT> using Gson library as below
ArrayList<OBJECT> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<OBJECT>>(){}.getType());
//or
ArrayList<OBJECT> yourArray = new Gson().fromJson(myjsonarray.toString(), new TypeToken<List<OBJECT>>(){}.getType());
Also while converting your ArrayList<OBJECT> to JsonArray, no need to convert it to string and back to JsonArray
JsonArray myjsonarray = new Gson().toJsonTree(MyArrayList<OBJECT>).getAsJsonArray();
Refer Gson API documentation for more details. Hope this will be helpful.
JSONArray is just a subclass of object, so if you want to get the JSONObjects out of a JSONArray into some other form, JSONArray doesn't have any convenient way to do it, so you have to get each JSONObject and populate your ArrayList yourself.
Here is a simple way to do it:
ArrayList<JSONObject> arrayList = new ArrayList(myJSONArray.length());
for(int i=0;i < myJSONArray.length();i++){
arrayList.add(myJSONArray.getJSONObject(i));
}
EDIT:
OK, you edited your code to show that you are using GSON. That is a horse of a different color. If you use com.google.gson.JsonArray instead of JSONArray, you can use the Gson.fromJson() method to get an ArrayList.
Here is a link: Gson - convert from Json to a typed ArrayList
Unfortunately, this will require a little work on your part. Gson does not support deserializing generic collections of arbitrary objects. The Gson User Guide topic Serializing and Deserializing Collection with Objects of Arbitrary Types list three options for doing what you want. To quote the relevant parts of the guide:
You can serialize the collection with Gson without doing anything specific: toJson(collection) would write out the desired output.
However, deserialization with fromJson(json, Collection.class) will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in fromJson. So, you have three options:
Option 1: Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use Gson.fromJson() on each of the array elements. This is the preferred approach. Here is an example that demonstrates how to do this.
Option 2: Register a type adapter for Collection.class that looks at each of the array members and maps them to appropriate objects. The disadvantage of this approach is that it will screw up deserialization of other collection types in Gson.
Option 3: Register a type adapter for MyCollectionMemberType and use fromJson with Collection<MyCollectionMemberType>
This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type Collection<MyCollectionMemberType>.
See the docs for details on each of the three options.
we starting from conversion [ JSONArray -> List < JSONObject > ]
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array)
throws JSONException {
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
jsonObjects.add(array.getJSONObject(i++))
);
return jsonObjects;
}
next create generic version replacing array.getJSONObject(i++) with POJO
example :
public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array)
throws JSONException {
ArrayList<Tt> tObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
tObjects.add( (T) createT(forClass, array.getJSONObject(i++)))
);
return tObjects;
}
private static T createT(Class<T> forCLass, JSONObject jObject) {
// instantiate via reflection / use constructor or whatsoever
T tObject = forClass.newInstance();
// if not using constuctor args fill up
//
// return new pojo filled object
return tObject;
}
Try this,
ArrayList<**YOUCLASS**> **YOURARRAY** =
new Gson().fromJson(oldJSONArray.toString(),
new TypeToken<List<**yourClass**>>(){}.getType());
Related
I have a JSON Like this
{ "video":{
"video_3745":{ },
"video_3437":{ },
"video_3471":{ },
"video_4114":{ }
}
}
In which every "video_xxxx" is of the SAME type. Is there a way to treat the "video" field as an array of that type? I need to iterate over all the videos, but the API is not sending them in an array, and I don't know how to model a class to receive this JSON without having to manually specify all the field names...
does GSON or LoganSquare have anything to help me out with this?
Try something like this
JSONObject video= json.getJSONObject("video"); // json is the whole response
Iterator x = video.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(video.get(key));
}
You can't treat them as an array, but with the org.json.JSONObject class you can get the list of keys and iterate over them. I believe in GSON the JsonObject.entrySet method will allow something similar.
https://developer.android.com/reference/org/json/JSONObject.html
https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html
I can't seem to find this anywhere, but tons of people have to be doing this.
I have an array of objects that I want to convert to a JSON String and post to a REST URL. Here's what I have so far:
if(history==null||history.length == 0){
return new String[0];
}
JSONArray array = new JSONArray();
for(DeviceHistory connectHistory:history){
array.put(connectHistory);
}
JSONObject response = jsonClient.remoteCall(SERVICE_NAME, array.toString());
The problem is that I get ["com.abc.model.connect.DeviceHistory#41e63298","com.abc.model.connect.DeviceHistory#41e63760","com.abc.model.connect.DeviceHistory#41e63c28","com.abc.model.connect.DeviceHistory#41e640f0"] from array.toString(). What am I doing wrong?
Because this is the result of Object.toString(). You may want to try:
https://code.google.com/p/google-gson/
This library allows to convert Object to JSON and back.
Your problem is that you are not passing your object as a String, so what you are writing in your JSON is a reference to your object.
You should implement your toString() method in that class if you can or just use it. However, if you cant you will need a helper method to achieve it.
It's been a while and i'm trying to ignore some frustrating issue i'm having with json things in java, i'm new to this and read alot however, parsing json in javascript or php was alot better (or easier i dunno) but now in java i cannot convert a jsonobject to jsonarray if it doesn't have a parent, cuz it uses .getJsonArray('array)
BUT what IF i have this :
{"49588":"1.4 TB","49589":"1.4 TB MultiAir","49590":"1.4 TB MultiAir TCT","49591":"1.6L MultiJet","49592":"1750 Tbi","49593":"2.0L MultiJet","49594":"2.0L MultiJet TCT"}
i'm not succeeding in anyway to convert it to array
what i want is to convert this JSONObject to JSONArray loop within its items and add them to a Spinner, now that's the first issue, the second question is: if i convert this to JSONArray how can i add the ID, Text to the spinner? just like the HTML Select tag
<option value="0">Item 1</option>
so it's an issue and a question hope someone can find the solution for this jsonarray thing, without modifying the json output from the website, knowing that if i modify and add a parent to this json, the JSONArray will work. but i want to find the solution for that.
Nothing special i have in the code:
Just a AsynTask Response, a log which is showing the json output i put at the beginning of this question
Log.d("response", "res " + response);
// This will work
jsonCarsTrim = new JSONObject(response);
// This won't work
JSONArray jdata = new JSONArray(response);
Thanks !
How about this:
JSONObject json = new JSONObject(yourObject);
Iterator itr = json.keys();
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<Integer> links = new ArrayList<Integer>();
int i = 0;
while(itr.hasNext()) {
String key = itr.next().toString();
links.add(i,Integer.parseInt(key));
entries.add(i, (CharSequence) json.getString(key)); //for example
i++;
}
//this is the activity
entriesAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.support_simple_spinner_dropdown_item, entries);
//spinner is the spinner the data is added too
spinner.setAdapter(entriesAdapter);
this should work (works for me), you may have to modify the code.
The way shown, i am adding all entries of the json object into a Spinner, where my json key is the index value and the linked String value of the json object will be shown as Spinner entry (title) in my activity.
Now when an Item is selected, fetch the SelectedItemPosition and you can look it up in the "links" array list, to get the real value.
I'm not sure if this is thing you want but give it a try. There is tutorial to convert the Json to Map. After you convert it, you can iterate through the map.
http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
What you have is a JSON object type, not an array type. To iterate you can get the Iterator from the keys method.
public void HelloWord {
for (int i = 0; i < 20; i++) {
Log.d("Great");
}
}
The code above doesn't work why?
I try to get value name
Does anybody know where is the problem?
org.json.JSONException: Value ...Content of link... at
org.json.JSON.typeMismatch at org.json.JSONArray.
I prefer to use the GSON library, as it is a fast and effective JSON parser. Once added to the project you will need to create classes to represent the data returned. You then can call a single function to create your objects for you:
gson.fromJson();
An exceptionally good article on the use of GSON can be found at http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html - it even uses Twitter for the example.
I think that you are missing the way that JSON works. Anything in {} is an Object, while [] designates an array. So the root of the twitter feed is a JSONObject, NOT a JSONArray:
Try something more like this:
JSONObject obj = new JSONObject(mStringBuilder.toString());
JSONObject trends = obj.getJSONObject("trends");
JSONArray today = trends.getJSONArray("2012-04-10");
for (int i = 0; i < today.length(); i++) {
JSONObject tag = today.getJSONObject(i);
String name = tag.getString("name");
// do whatever with name
}
Much easier, and its clearer how it works. JSONObjects are dictionaries, with a simple mapping between keys and values - each Object ({}) can contain either more objects, or arrays ([]) which can contain either simple integers or more objects
This is the json response from my server . How can i parse it and store it in HashMap? Please help me.
{'records':
[{
'number':165,
'description': 'abcd'
},
{
'number':166,
'description': 'ab'
},
{
'number':167,
'description': 'abc'
}]
}
im new in android but maybe you can do something like this:
JSONObject JsonObject = new JSONObject(json);
JSONArray JsonArray_ = JsonObject .getJSONArray("records");
for (int i = 0; i < numberOfItems; i++) {
JSONObject record= JsonArray_photo.getJSONObject(i);
parsedObject.number = record.getString("number"); //its the same for all fields
map.add(parsedObject);
}
I done something like that for my own JSON parser. hope this helps. cheers
I suggest you look at the gson library, which makes it very easy indeed to parse JSON into an object representing the data. So you could create a Record object, with public member variables for number, description, and then use gson to parse the JSON into an object array.
http://code.google.com/p/google-gson/
Add the .jar to your libs folder and then use it like this:
Record[] records = new GsonBuilder().create().fromJson(jsonString,Record[].class)
int number = record[0].number;
The org.json package is included in Android: http://developer.android.com/reference/org/json/package-summary.html
Use is simple:
JSONObject json_object = new JSONObject(String json_string);
Each property can then be accessed as a Java property, e.g. json_object.property. It will throw a JSONException if the parsing fails for some reason (i.e., invalid JSON).
You can use Gson library, you can find full tutorial on softwarepassion.com