0

I'm having a string like below

MyString

[{"id":123,"name":"Abc"},{"id":124,"name":"EDF"}]

I need to convert/map this into my class(Test) using Set

Test

public class Test {
    int id;
String name;
}

I've tried with the following method but didn't get succeed.

    Set<Test> meds = (Set<Test>) (Object) MyString;

The Exception is

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Set

Jayendran
  • 9,638
  • 8
  • 60
  • 103
  • String to Set directly ? That is not possible. You need to build your objects from String first. – Suresh Atta Feb 27 '18 at 10:24
  • Please convert the String into objects first. then you can pass them. second option you can convert the string in to Json format and use the Object Mapper in the Code part. – Lova Chittumuri Feb 27 '18 at 10:27

2 Answers2

0

This is a json object, you will need to use a parser. Look into GSON, for example.

Lance Toth
  • 430
  • 3
  • 17
0

Use Jackson library for convertation your String to Set of objects.

You cannot convert it directly.

TypeReference<Set<Test>> ref = new TypeReference<Set<Test>>() {};
try {
    new ObjectMapper().readValue("[{\"id\":123,\"name\":\"Abc\"},{\"id\":124,\"name\":\"EDF\"}]", ref);
} catch (IOException ignored) {
    // stub
}

And of course do not forgot to add getters and setters into your Test class

beowulf13th
  • 447
  • 1
  • 6
  • 16