I have some data in my DB and i want to put that data in serialized JSON format. How do I do that using GSON serialization?
The examples available do not show how to get the data and then insert it in the format.
ANSWER
Gson manJson = new Gson();
ArrayList<MyTableName> list=new ArrayList<MyTableName>();
for(int i=0;i<count;i++){
cursor2.moveToNext();
MyTableName data=new MyTableName();
data.setMyVal(cursor2.getString(cursor2.getColumnIndex("MyVal")));
list.add(data);
}
String jsonData=manJson.toJson(list);
This worked for me....
Related
so I have this JSON in string format:
[
"1.0",
"1.1",
"1.2"
]
but I need to convert it to ArrayList In Kotlin ? I have tried to find, but most of the answer are in Java. if using gson in Java maybe it will be like this. but I am a beginner and I failed to convert the code below to Kotlin
Gson gson = new GsonBuilder().create();
ArrayList<String> theList = gson.fromJson(stringObject, new TypeToken<ArrayList<String>>(){}.getType())
what should I do to convert that json string to array list in Kotlin ?
Maybe this is the kotlin code you want, converted from your Java code:
val gson = GsonBuilder().create()
val theList = gson.fromJson<ArrayList<String>>(stringObject, object :TypeToken<ArrayList<String>>(){}.type)
my question is about the following.
Im just trying to generate a new txt file in my internal storage. Inside it i will have just an array converted to string to save some IDs that i need to persist.
After that i need to read that file too but i don't know how to start.
I think is something like this:
private void GsonWriter(ArrayList<Integer> arrayListTouched){
String str = arrayListTouched.toString();
Gson gson = new GsonBuilder().create();
Since you're already using Gson.
How to save it.
Gson gson = new GsonBuilder().create();
ArrayList<Integer> array = new ArrayList<>(); // Integer in your case. But can be any type
// save this string
String arrayString = gson.toJson(array);
How to load it.
ArrayList<Integer> array = gson.fromJson(arrayString, new TypeToken<ArrayList<Integer>>(){}.getType());
I assume you know how to save/load the string
How to Convert this
[{destLocId=10, createdUserId=b9ab2d71-9a69-4ba3-b498-d36446a154d6,
createdDate=2016-6-29 14:35:00}]
to this :
[{"destLocId":10, "createdUserId":b9ab2d71-9a69-4ba3-b498-d36446a154d6,
"createdDate":2016-6-29 14:35:00}]
You can use GSON library for converting ArrayList to JSON. Here an example,
ArrayList<String> bibo = new ArrayList<String>();
bibo.add("obj1");
bibo.add("obj2");
bibo.add("obj3");
String json = new Gson().toJson(bibo);
And this example from Gson User Guide to use it on collection.
How i can pass ArrayList<byte[]> to JSONObject as a parameter?
For example, I need to send a Id (string), Name (string) and photoList (ArrayList<byte[]>) in a json object.
You can use GSON LIBRARY . The code you need can be as :
String jso;
jso = new Gson().toJson(photoList);
It should convert the arraylist(i.e. photoList) to jsonObject.
Just use GSONlib for this if you want to convert arraylist into json
If you are using GSON library use the following code to convert your ArrayList to JSON.
String jsonString = new Gson().toJson(yourArrayList);
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());