简体   繁体   English

使用Java 8将String列表转换为Object列表

[英]Using Java 8 to convert a list of String into a list of Object

There is a stream read from file, the content of each line is like: 有一个从文件读取的流,每一行的内容如下:

 {"uid":"5981865218","timestamp":1525309552069,"isHot":true}

The class of User: 用户类别:

public class User {
    private String uid;
    private long timestamp;
    private boolean isHot;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public boolean getIsHot() {
        return isHot;
    }

    public void setIsHot(boolean isHot) {
        this.isHot = isHot;
    }
}

The code that I want to get a list of Object 'List' from file stream: 我想从文件流中获取对象“列表”列表的代码:

BufferedReader targetBr = null;
targetBr = new BufferedReader(new FileReader(targetUsersFile));
List<User> tmpUsers = targetBr.lines().?I don't know how process in there?.collect(Collectors.toList());

You need to deserialize the String to User objects. 您需要将String反序列化为User对象。 I have used Jackson ObjectMapper here (you could very well use others like Gson). 我在这里使用过Jackson Jackson ObjectMapper (您可以很好地使用Gson等其他产品)。

ObjectMapper objectMapper = new ObjectMapper();
...
targetBr.lines()
        .map(line -> {
            try {
                return objectMapper.readValue(line, User.class);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

The map part of the stream takes a Function and hence you cannot throw a checked exception from there. 流的map部分带有一个Function ,因此您不能从那里抛出一个检查异常。 Hence, I have wrapped the IOException that Jackson readValue throws (could throw) into a RuntimeException. 因此,我将Jackson的readValue抛出(可能抛出)的IOException封装到RuntimeException中。 You might have to change that part according to your need. 您可能需要根据需要更改该部分。

This is just a start. 这只是一个开始。 Think about what to do when there is an invalid entry that cannot be deserialized into a User . 考虑当存在无法反序列化为User的无效条目时该怎么办。 Some specific corner cases: 一些特定的极端情况:

  1. What if there is an unrecognized field (a property that is not present in the User class) in the input string. 如果输入字符串中存在无法识别的字段(User类中不存在的属性),该怎么办。 ObjectMapper in this case throws an UnrecognizedPropertyException exception. 在这种情况下,ObjectMapper抛出UnrecognizedPropertyException异常。 You can find ways to ignore it. 您可以找到忽略它的方法。
  2. What if one or more of fields in the User class is missing in the String... Are some/all of them mandatory...? 如果“字符串”中缺少User类中的一个或多个字段,该怎么办...其中某些/全部是强制性的...?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM