Home > Enterprise >  How to convert list of map as string to list of Map<String,String> or list<Pojo>
How to convert list of map as string to list of Map<String,String> or list<Pojo>

Time:05-08

i have a string "[{id=123, customername=john}]" i want to convert it into List<Map<String,String>> or List<Pojo> , i tried using gson library to convert into List<Map<String,String>> but Method threw 'com.google.gson.JsonSyntaxException' exception as gson accepts first argument as json string and this is not a json string, i can convert into json string and pass to gson function or object mapper function with use of pattern, just want to avoid that , is there any way to convert the string into List<Map<String,String>> or List class, i also followed the thread how to convert below string to list of map? but this throws com.google.gson.JsonSyntaxException

CodePudding user response:

Supposing that your List only contains strings that respect the format of the Map.toString() method, then we could simply stream the List and map each String to its corresponding Map.

To do so, I've first removed the curly brackets from the String. Then, I've split the String by a comma to retrieve an array representing the Map's entries. At this point, the entries are iterated and split in turn to yield the key and its corresponding value. Ultimately, the resulting Map is returned.

In the sample below, I've included a Main to test whether the List<String> actually corresponds to the List<Map<String, String>>.

class Main {
    public static void main(String[] args) {
        //Printing the list of strings
        List<String> list = new ArrayList<>(List.of("{id=123, customername=john}", "{id=234, customername=ben}", "{id=555, customername=jeff}"));
        System.out.println(list);

        //Streaming the list with the maps represented as strings
        List<Map<String, String>> listRes = list.stream().map(e -> {
            //Removing the brackets from the string and splitting the map's entries by comma
            String[] entries = e.replaceAll("[\\{\\}]", "").split(",");
            
            //Splitting each entry by the equal sign and then adding the entry within the map to return
            Map<String, String> map = new HashMap<>();
            String[] vetEntryTemp;
            for (String entry : entries) {
                vetEntryTemp = entry.trim().split("=");
                map.put(vetEntryTemp[0], vetEntryTemp[1]);
            }
            return map;
        }).collect(Collectors.toList());

        //Printing the list of maps to check if matches with the original one
        System.out.println(listRes);
    }
}

CodePudding user response:

Assuming the strings were separated by some other delimiter you can do it like this. The delimiter here is #to separate the two records.

  • \\s* - is 0 or more white space characters
  • [=,] - is a character class of an equals and comma
  • first split on # to separate the records.
  • then map to a HashMap by
    • splitting on either = or , and creating a map using the array values. The map is cast to its interface type.
  • the convert to a list.
String s =
        "id=123, customername=john#id=134,customername=Mary";
List<Map<String, String>> mapList =
        Arrays.stream(s.split("\\s*#\\s*"))
        .map(ss -> {
            String[] arr = ss.split("\\s*[=,]\\s*");
            return (Map<String,String>)new HashMap<>(
                    Map.of(arr[0], arr[1], arr[2], arr[3]));
        }).toList();

mapList.forEach(System.out::println);

prints

{customername=john, id=123}
{customername=Mary, id=134}

Here is converting it to an Pojo class. The process is the same as for a map except the id and name are position independent in the constructor. So just use the actual values and not the keys.

List<Pojo> pojoList =
        Arrays.stream(s.split("\\s*#\\s*"))
        .map(ss -> {
            String[] arr = ss.split("\\s*[=,]\\s*");
            return (Pojo) new Pojo(arr[1], arr[3]);
        }).toList();

pojoList.forEach(System.out::println);

prints

[123, john]
[134, Mary]

And here is the class that was used

class Pojo {
    private String id;
    private String customername;
    
    public Pojo(String id, String customername) {
        this.id = id;
        this.customername = customername;
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getCustomername() {
        return customername;
    }
    
    public void setCustomername(String customername) {
        this.customername = customername;
    }
    
    @Override
    public String toString() {
        return "[%s, %s]".formatted(id, customername);
    }
    
}
  • Related