我想转换一个人的json数组
persons: [
{"1, Franck, 1980-01-01T00:00:00"},
{"2, Marc, 1981-01-01T00:00:00"}
]
使用此类的 Person 对象列表:
class Person {
private Integer id;
private String name;
private Date dateOfBirth;
// getter and setter
}
是否可以使用转换器和 Java 8 来实现?
public Person convert(String from) {
String[] data = from.split(",");
return new Person(Integer.parseInt(data[0]), data[1], new Date(data[2]));
}
最佳答案
你可以这样做,
Pattern idNumber = Pattern.compile("\\d+");
List<Person> persons = Arrays.stream(from.split("}")).filter(s -> idNumber.matcher(s).find())
.map(s -> s.substring(s.indexOf("{") + 1)).map(s -> s.split(","))
.map(a -> new Person(Integer.parseInt(a[0].replaceAll("\"", "")), a[1],
LocalDateTime.parse(a[2].trim().replaceAll("\"", ""))))
.collect(Collectors.toList());
第一个split
每个字符串使用“}”字符,然后过滤掉不包含数字的无效 token 。请注意,每个有效负载都应包含一个数字 ID 号。最后删除 Id 数字之前出现的任何虚假尾随字符并映射每个结果 String
到 Person
目的。最后collect
Person
实例到 List
.
注意我使用了LocalDateTime
对于 dateOfBirth
Person
中的字段类(class)。所以 Person
类看起来像这样。
public class Person {
private final Integer id;
private final String name;
private final LocalDateTime dateOfBirth;
// remainder omitted for the sake of brevity.
}
然而,如您所见,使用 Jackson 等框架总是很直观 ObjectMapper
完成工作而不是编写所有这些。但在这种情况下,您的 Json 格式不正确,因此除非您修复 json 有效负载结构,否则您将无法使用这样的框架。
更新
这是更优雅的 Java9 解决方案。
String regexString = Pattern.quote("{\"") + "(.*?)" + Pattern.quote("\"}");
Pattern pattern = Pattern.compile(regexString);
List<Person> persons = pattern.matcher(from)
.results()
.map(mr -> mr.group(1)).map(s -> s.split(", "))
.map(a -> new Person(Integer.parseInt(a[0]), a[1], LocalDateTime.parse(a[2])))
.collect(Collectors.toList());
在 Java 9 中,您现在可以使用 Matcher#results()
得到 Stream<MatchResult>
.这是 documentation 的摘录.
Returns a stream of match results for each subsequence of the input sequence that matches the pattern. The match results occur in the same order as the matching subsequences in the input sequence.
我宁愿推荐你使用 Java9 来解决这个问题。
如果您只需要为 List
做这件事的 String
Person
的代表,你可以这样做。
List<String> personStr = Arrays.asList("1, Franck, 1980-01-01T00:00:00", "2, Marc, 1981-01-01T00:00:00");
List<Person> persons = personStr.stream()
.map(s -> s.replaceAll(" ", "").split(","))
.map(a -> new Person(Integer.parseInt(a[0]), a[1], LocalDateTime.parse(a[2])))
.collect(Collectors.toList());
请注意,后者比前者简单得多,并且仅包含原始解决方案的一个子集。
关于class - Java将具有逗号分隔值的字符串列表转换为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795363/