如何将字符串转换回对象?我有以下课程:
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
必须通过转换为string
来处理,例如,此后,我们得到以下字符串:
[Test{name='name1', value='value1', testing='testing1'}, Test{name='name2', value='value2', testing='testing2'}, Test{name='name3', value='value3', testing='testing3'}]
然后如何将字符串转换回Test
的对象列表?
有人可以帮忙吗?
答案 0 :(得分:1)
如果您不需要完全这种toString
模式,而只需将您的Object
转换为易于理解的格式,然后再转换回{{1} },您可以像杰克逊Object
这样无缝地 marshal 进行json并 parse 回到Object
。有关快速入门,请参见https://www.baeldung.com/jackson-object-mapper-tutorial。
答案 1 :(得分:0)
您可以创建其他构造函数,并使用以下字符串调用它们:
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);
}
}
}