I'm trying to convert Generic ArrayList in JSONArray but it is displaying null value.
but this is working fine if i'm trying to display specific value from ArrayList.
ArrayList<myClass> experience = new ArrayList<>();
... //adding some values
Log.v("testing", experience.get(0).company); //this is showing value
JSONArray json = new JSONArray(experience);
Log.v("testing", json.toString()); //this is showing [null]
There might be a problem recognizing andn converting your "myClass" bean to json.
Try using gson library to create json and to parse it back to object .
Can use GSON library like this:
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
Replace with Below Code and try it will work.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(experience);
Log.e("Jason Array", json);
Related
I'm trying to covert Java object to json using Gson library, but its not working as expected and returning empty string,
my code:
String ie = new String("Jack");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
it returns:
{}
Please let me know if anything wrong with library, I tried with other Objects as well all returning null value like for Intent Object, ApplicationInfo etc
If you want convert string to json object, your string must be json as well.
For example:
String ie = new String("{\"name\": \"Jack\"}");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
I used jackson to convert json strings to json objects / arrays like so:
JSONObject jsonObj = XML.toJSONObject(myXmlString);
JSONObject userObj = jsonObj.getJSONObject("user"); // is there a GSON version of this?
JSONArray orders = userObj.getJSONArray("orders");
My main question is: is there a GSON version of getting json objects / arrays without converting to a pojo? My json is very complex so it's difficult to create pojos.
Secondly, does gson allow you to convert an xml string to json like jackson does (line 1)?
For the first question:
You can create a JsonObject from a json string
String json = "{ \"key1\": \"value1\", \"key2\": false}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
otherwise you can create a Map object
String jsonString = "{'employee.name':'Bob','employee.salary':10000}";
Gson gson = new Gson();
Map map = gson.fromJson(jsonString, Map.class);
for reference: https://www.baeldung.com/gson-json-to-map
For the second question:
I found this question in stackoverflow
is there a GSON version of getting json objects / arrays without
converting to a pojo?
Something like this can do the job
import com.google.gson.*;
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(myJsonString);
//get as object
JsonObject obj = json.getAsJsonObject();
//get as array
JsonArray arr = json.getAsJsonArray();
does gson allow you to convert an xml string to json like jackson does
No
I'm trying to build a JsonArray of JsonObjects using gson.
Each JsonObject will take the following format,
{"image":"name1"}
{"image":"name2"}
and so on.
I have a string array of the names ("name1","name2",...)
I cannot convert string array directly in to a JsonArray. I'm trying to create JsonObjects iteratively and add it to a JsonArray.
JsonObject innerObject;
JsonArray jArray = new JsonArray();
for(int i = 0; i<names.length; i++)
{
innerObject = new JsonObject();
innerObject.addProperty("image",names[i]);
jArray.add(innerObject);
}
But as I understand, add method in JsonArray takes a JsonElement and here I'm giving a JsonObject. I couldn't find a way to convert JsonObject to JsonElement.
The whole point of using gson will be gone when I do this. Is there a better way?
First, create a class that represents a single json object, e.g.:
class MyObject {
private String image;
public MyObject(String name) { image = name; }
}
Gson will use the class' variable names to determine what property names to use.
Then create an array or list of these using the data you have available, e.g.
ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));
Finally, to serialize to Json, do:
String json = new Gson().toJson(allItems);
And to get the data back from json to an array:
MyObject[] items = new Gson().fromJson(json, MyObject[].class);
For simple (de)serialization, there is no need to be dealing directly with Json classes.
If you are going to use GSON use it like this to convert to object
List<Image>images = new Gson().fromJson(json, Image[].class);
To get json string
String json = new Gson().toJson(images);
That's the point of gson you should not manipulate the data with loops and stuff. You need to take advantage of its powerful model parsing.
Maybe too late but... There is a way to do without creating a new class if you dont need it:
import com.google.gson.JsonObject;
import com.google.gson.JsonArray
...
...
JsonArray jobj = new JsonArray();
String[] names = new String[]{"name1","name2","name3"};
for(String name : names) {
JsonObject item = new JsonObject();
item.addProperty("name",name);
jobj.add(item);
}
System.out.println(jobj.toString());// ;)
Lets say I have following list of custom object: ArrayList<GroupItem> where GroupItem is some class that has int and String variables.
I tried so far Gson library but it's not exactly what I want.
ArrayList<GroupItem> groupsList = /* ... */
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(groupsList, new TypeToken<ArrayList<GroupItem>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
My goal is to get JSONArray (org.Json.JSONArray) somehow. Any ideas?
[EDIT]
My project is Android with Cordova that has API based on org.Json.JSONArray
ANd I thought to write some generic way to convert instances to JSONArray / JSONObject
Thanks,
This way is worked for me:
Convert all list to String.
String element = gson.toJson(
groupsList,
new TypeToken<ArrayList<GroupItem>>() {}.getType());
Create JSONArray from String:
JSONArray list = new JSONArray(element);
The org.json based classes included in Android don't have any features related to converting Java POJOs to/from JSON.
If you have a list of some class (List<GroupItem>) and you absolutely need to convert that to a org.json.JSONArray you have two choices:
A) Use Gson or Jackson to convert to JSON, then parse that JSON into a JSONArray:
List<GroupItem> list = ...
String json = new Gson().toJson(list);
JSONArray array = new JSONArray(json);
B) Write code to create the JSONArray and the JSONObjects it will contain from your Java objects:
JSONArray array = new JSONArray();
for (GroupItem gi : list)
{
JSONObject obj = new JSONObject();
obj.put("fieldName", gi.fieldName);
obj.put("fieldName2", gi.fieldName2);
array.put(obj);
}
Why do you want to use GSON to convert to an org.json class? Nor do you need to write any custom code to get a JSONArray. The org.json api provides a way to do it.
LinkedList list = new LinkedList();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
JSONArray jsonArray = new JSONArray(list);
System.out.print(jsonArray);
Use Jackson for JSON to Object or Object to JSON
See the next link Jackson examples
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, groupsList );
System.out.println("groupsList JSON is\n"+stringWrite);
You don't need gson. There's a constructor that takes a collection, so just:
ArrayList<GroupItem> groupsList =... ;
JSONArray JSONArray = new JSONArray(groupsList);
I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:
// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();
I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?
My array looks something like:
[item1,item2,item3]
You have 2 choices :
Manually parse the string and recreate the arraylist. This would be pretty tedious.
Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Try this
ArrayList<String> array = Arrays.asList(arrayString.split(","))
This will work if comma is used as separator and none of the items have it.
The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:
Type type = new TypeToken<List<T>>(){}.getType();
List<T> list = gson.fromJson(jsonString, type)
perhaps it will be helpful.
//arraylist convert into String using Gson
Gson gson = new Gson();
String data = gson.toJson(myArrayList);
Log.e(TAG, "json:" + gson);
//String to ArrayList
Gson gson = new Gson();
arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
{}.getType());
I ended up using:
ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\\s*,\\s*")));
This doesn't work for all array types though. This option differs from:
ArrayList<String> array = Arrays.asList(arrayString.split(","));
on that the second option creates an inmutable array.
Update to Dhruv Gairola's answer for Kotlin
val gson = Gson();
val jsonString = gson.toJson(arrayList)