Arghya Pal
Arghya Pal

Reputation: 5

Is there any way to convert string [which is an object some class] to object of some class?

private static void method() {
List<HashMap<Integer, String>> repeating = new ArrayList<>();

for(int i = 0; i < 5; i++) {
  HashMap<Integer, String> group = new HashMap<>();
  group.put(958, "958value-" + i);
  group.put(959, "959value-" + i);
  group.put(960, "960value-" + i);
  repeating.add(group);
}

/*Is there any way to change listObj to again List object*/
String listObj = repeating.toString();}

I will be getting string of List object which I want to convert to List object. Is there any way to convert that string to List?

Upvotes: 0

Views: 54

Answers (3)

Andriy Zayats
Andriy Zayats

Reputation: 31

You can use serialization instead of toString. Take a look at Gson / Jackson. That libraries allow convert object to string and parse string to object back.

Gson for example allows you to transform any object to a JSON and then back to the object this way:

List<String> list1 = new ArrayList<>();
// Populate the list
Gson gson = new Gson();
String jsonifiedList = gson.toJson(list1);

Then do what you need with the String form of the list and retrieve it:

List<String> list2 = gson.fromJson(jsonifiedList, new TypeToken<List<String>>(){}.getType());

If your list contains more complex objects, you may need to add a JsonSerializer to your Gson object so it knows how to create and parse the JSON.

Upvotes: 1

Aurele Collinet
Aurele Collinet

Reputation: 138

Yes it should be possible although i didn't get everything from you question

Create a List of the object List

then iterate your map with

 for (Map.Entry<String, String> entry : yourmap.entrySet()) {
          new List<YourObject> lst;
          lst.add(new Object(entry.getkey, entry.getvalue));

but i suggest you dont use and map i dont see why you need it prefer a list an arraylist if you want to iterate on it

Upvotes: 0

ewramner
ewramner

Reputation: 6233

In the general case the answer is no. In some cases the toString method for a class generates a string that is compatible with a corresponding parse method or constructor in the class. Then you can convert back. Normally information is lost when an object is converted into a string format.

Upvotes: 0

Related Questions