2016-04-29 132 views
0

我有一个响应字符串,如下所示,我需要解析它并将其存储在我的类中。格式如下所示:然后这条虚线-------------其也固定 解析特定格式的字符串

  • 然后刚好低于key:value

    • 任务名称。它可以有许多键值对

    下面是响应字符串。

    abc------------- 
    Load:79008 
    Peak:4932152 
    
    def------------- 
    Load:79008 
    Peak:4932216 
    
    ghi------------- 
    Load:79008 
    Peak:4874588 
    
    pqr------------- 
    Load:79008 
    Peak:4874748 
    

    下面是我的课:

    public class NameMetrics { 
    
        private String name; 
        private Map<String, String> metrics; 
    
        // setters and getters 
    
    } 
    

    在上面的类,nameabcmetrics地图应该有Load为关键和79008作为值,并同其他键:值对。我想使用正则表达式,但不知道我是否可以在这里使用正则表达式。

    private static final Pattern PATTERN = Pattern.compile("(\\S+):\\s*(\\S*)(?:\\b(?!:)|$)"); 
    
    String response = restTemplate.getForObject(url, String.class); 
    // here response will have above string. 
    

    这样做的最好方法是什么?

  • +2

    正则表达式不需要,只需逐行迭代输入 – anubhava

    +1

    阅读线。跳过空白行。如果'line.indexOf(':')'返回-1,那么你有一个“header”行,否则你有一个key:value对,所以'substring()'键和值。冲洗并重复。 – Andreas

    回答

    2
    BufferedReader reader = new BufferedReader(...???...); 
    NameMetrics current = null; 
    List<NameMetrics> result = new ArrayList<>(); 
    while (true) { 
        String s = reader.readLine(); 
        if (s == null) { 
        break; // end reached 
        } 
        if (s.trim().isEmpty()) { 
        continue; // Skip empty line 
        } 
        int cut = s.indexOf(':'); 
        if (cut == -1) { 
        cut = s.indexOf('-'); 
        if (cut == -1) { 
         continue; 
        } 
        current = new NameMetrics(); 
        current.setName(s.substring(0, cut)); 
        result.add(current); 
        } else if (current != null) { 
        current.setMetrics(s.substring(0, cut), s.substring(cut+1)); 
        } 
    } 
    
    +0

    要填写'... ??? ...',你可以使用'new StringReader(response)'。 – 4castle