[英]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: ArrayList testing
必须通过转换为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
?那么如何将字符串转换回
Test
对象列表?
Can anyone help on it?任何人都可以帮忙吗?
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
.如果您并不完全需要那个
toString
模式,而只需要将您的Object
转换为人类可读的内容而不是返回一个Object
,您可以封送 json 并使用 Jackson ObjectMapper
类的东西无缝地解析回Object
。 See https://www.baeldung.com/jackson-object-mapper-tutorial for a quick-start.有关快速入门,请参阅https://www.baeldung.com/jackson-object-mapper-tutorial 。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.