java snakeyaml解决Map&List&对象嵌套解析问题

时间:2025-04-05 07:29:13

引入相关jar包依赖

<dependency>
    <groupId></groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.25</version>
</dependency>

 

待解析yaml文件

# 
orgs:
  Org1MSP:
    - nodeName: peer0.
      grpcUrl: grpc://127.0.0.1:7051
      evenHubUrl: grpc://127.0.0.1:7053
    - nodeName: peer1.
      grpcUrl: grpc://127.0.0.1:8051
      evenHubUrl: grpc://127.0.0.1:8053
  Org2MSP:
    - nodeName: peer0.
      grpcUrl: grpc://127.0.0.1:9051
      evenHubUrl: grpc://127.0.0.1:9053
    - nodeName: peer1.
      grpcUrl: grpc://127.0.0.1:10051
      evenHubUrl: grpc://127.0.0.1:10053

visitors:
  ayz3jmhtRBd2sidLl0Y3Eq4tyGmhpDUf:
    name: 
    mspId: Org2MSP
    keystore: /home/org2/keystore/admin2keystore_sk
    signcerts: /home/org2/signcerts/Admin@-
  byz3jmhtRBd2sidLl0Y3Eq4tyGmhpDUf:
    name: 
    mspId: Org1MSP
    keystore: /home/msp/keystore/adminkeystore_sk
    signcerts: /home/msp/signcerts/Admin@-

 

yaml对应实体类

public class NetworkConfig {
    private Map<String, MspInfo> visitors;

    private Map<String, List<PeerNodeDTO>> orgs;

    public Map<String, MspInfo> getVisitors() {
        return visitors;
    }

    public void setVisitors(Map<String, MspInfo> visitors) {
        this.visitors = visitors;
    }

    public Map<String, List<PeerNodeDTO>> getOrgs() {
        return orgs;
    }

    public void setOrgs(Map<String, List<LinkedHashMap<String, String>>> orgs) {
        final Map<String, List<PeerNodeDTO>> tmpOrgs = new HashMap<>();
        orgs.forEach((k, v) -> {
            List<PeerNodeDTO> peerNodeDTO = JSONObject.parseObject(
                    JSONObject.toJSONString(v), new TypeReference<List<PeerNodeDTO>>(){});
            tmpOrgs.put(k, peerNodeDTO);
        });
        this.orgs = tmpOrgs;
    }
}

 

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PeerNodeDTO implements Serializable {
    private static final long serialVersionUID = -2922948409432264522L;
    private String nodeName;
    private String grpcUrl;
    private String evenHubUrl;
}

 

解析相关代码

public class App {
    public static void main(String[] args) throws Exception {
        File visitor = ResourceUtils.getFile("classpath:");
        Yaml yaml = new Yaml();
        NetworkConfig networkConfig = yaml.loadAs(new FileInputStream(visitor), NetworkConfig.class);
        // ...
    }
}