Java convert ArrayList to string and back to ArrayList? - java

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)

Related

Android: gson.toJson converter giving empty string for Android objects

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);

Json into Array

I am reading a JSON file into one string and one array. I already have a string where the JSON is saved, let's call it myString. Here is the JSON file:
As you can see, the file contains three styles, from "styleCount": "3". My goal is to now create three string variables for each style, similar to the following pseudo variables:
String name_style1 should contain: "Sommer-Fashion"
String name_style2 should contain: "Dream-Style"
String name_style3 should contain: "Perfect-Look"
Then I need an array of strings for each style with the SKU numbers:
private String[] sku_style1 = new String[6];
sku_style1[0] = "392714";
sku_style1[1] = "395895";
sku_style1[2] = "392450";
sku_style1[3] = "371706";
sku_style1[4] = "383748";
sku_style1[5] = "385275";
And also for the other styles:
private String[] sku_style2 = new String[6];
private String[] sku_style3 = new String[6];
Is there a function of Java which helps with simply adding elements from a JSON file (or in my case a string: myString) into a string and an array?
Any help is appreciated.
Google GSON! No functions native to Java really help much, but Google GSON has helped me numerous times with issues much harder than this. I think you'll find it very helpful. Here is a link!
https://mvnrepository.com/artifact/com.google.code.gson/gson
EDIT
This link is for the repository for the jar downloads!
EDIT 2
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
There are JSON parson libraries that serve this exact purpose.
JSONArray
JSONString
Read more here.

how to convert Arraylist<myClass> in JSONArray

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);

Gson, creating a simple JsonArray of JsonObjects

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());// ;)

convert arrayList multimap to json string?

I have the following code:
public static void postHttpStream(ArrayListMultimap<String, String> fcmbuildProperties){
HttpClient client = new HttpClient();
Gson gson = new Gson();
System.out.println(fcmbuildProperties);
String jsonString = gson.toJson(fcmbuildProperties);
System.out.println(jsonString);
}
where fcmbuildProperties is an ArrayListMultimap. I try to convert that to JSON here: String jsonString = gson.toJson(fcmbuildProperties); But this returns an empty array. What do I need to do instead?
This is the input that fcmbuildProperties contain : {build.name=[test_project], build.timestamp=[1425600727488], build.number=[121]}
I need to convert this to Json. with key/values.
Use ArrayListMultimap#asMap()
String jsonString = gson.toJson(fcmbuildProperties.asMap());
Gson considers ArrayListMultimap as a Map and ignores its internal state which actually manages the multimap. asMap returns a corresponding Map instance which you can serialize as expected.

Categories