ratzip
ratzip

Reputation: 1671

How to convert String back to Object List in Java

How to convert the string back to object? I have the following class:

class Test {
    String name;
    String value;
    String testing;

    @Override
    public String toString() {
        return "Test{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", testing='" + testing + '\'' +
                '}';
    }
}

class Testing {
   private List<Test> testing = new ArrayList<Test>();
   handling(testing.toString())
   public String handling(String testing) {
        // do some handling and return a string
   }
}

ArrayList testing must handled by convert to string, for example, after that, we get the following string:

[Test{name='name1', value='value1', testing='testing1'}, Test{name='name2', value='value2', testing='testing2'}, Test{name='name3', value='value3', testing='testing3'}]

then how to convert the string back to object list of Test?

Can anyone help on it?

Upvotes: 0

Views: 3431

Answers (2)

wake-0
wake-0

Reputation: 3968

You can create an additional constructor and call them with the string:

class Test {
    private String name;
    private String value;
    private String testing;

    Test(string objString) { 
        Pattern pattern = Pattern.compile("name=('.+'), value=('.+'), testing=('.+')");
        Matcher matcher = pattern.matcher(objString);
        if (matcher.matches()) {
            name = matcher.group(1);
            value = matcher.group(2);
            testing = matcher.group(3);
        } else {
            throw new ArgumentException("Cannot parse"):
        }
    }

    @Override
    public String toString() {
        return "Test{" +
                "name='" + name + "'" +
                ", value='" + value + "'" +
                ", testing='" + testing + "'" +
                '}';
    }
}

class Testing {
    doTesting(List<Test> testing) {
        List<String> testingAsString = new ArrayList<String>();
        // To string
        for (Test t : testing) {
            testingAsString.add(t.toString());
        }
        List<Test> clonedTesting = new ArrayList<Test>();
        // To Test
        for (String t : testingAsString) {
            clonedTesting.add(new Test(t));
        }

        // Here every test string is again an object of type Test
        for (Test t : clonedTesting) {
            System.out.println(t);
        }
    }  
}

Upvotes: 0

Davide
Davide

Reputation: 136

If you don't need exactly that toString pattern, but only need to convert your Object to something human-readable and than back to an Object, you could marshal to json and parse back to Object seamlessly with something like Jackson ObjectMapper. See https://www.baeldung.com/jackson-object-mapper-tutorial for a quick-start.

Upvotes: 1

Related Questions