将String(使用Regex)转换为可用对象

时间:2017-04-06 09:34:09

标签: java json regex

对于一个项目,我们正在使用一个telnet服务器来接收我们的数据。 从telnet连接读取一行后,我得到以下字符串:

原始字符串:

SVR GAME MOVE {PLAYER: "PLAYER", MOVE: "1", DETAILS: ""}

我试图将其转换为输出,我可以轻松使用而不会发生太多可利用性。 所需的格式是轻松获得(PLAYER)或获得。我尝试将regex与json结合使用,请参阅下面的代码:

String line = currentLine;
line = line.replaceAll("(SVR GAME MOVE )", ""); //remove SVR GAME MATCH
line = line.replaceAll("(\"|-|\\s)", "");//remove quotations and - and spaces (=\s)
line = line.replaceAll("(\\w+)", "\"$1\""); //add quotations to every word
JSONParser parser = new JSONParser();
try {
       JSONObject json = (JSONObject) parser.parse(line);
       //@todo bug when details is empty causes
       //@todo example string: SVR GAME MOVE {PLAYER: "b", MOVE: "1", DETAILS: ""}
       //@todo string that (line) that causes an error when parsing to json {"PLAYER":"b","MOVE":"1","DETAILS":}
       //@todo Unexpected token RIGHT BRACE(}), i think because "details" has no value
       System.out.println(json.get("PLAYER"));
       System.out.println(json.get("MOVE"));
       System.out.println(json.get("DETAILS"));
       int index = Integer.valueOf(json.get("MOVE").toString());
       for(GameView v : views){
          v.serverMove(index);//dummy data is index 1
       }
    } catch (ParseException e) {
        e.printStackTrace();
}

问题是当细节为空时,这将导致意外的令牌RIGHT BRACE(})。此外,当玩家在其名称中使用剥削性名称(例如引号)时,代码将很容易崩溃。

将原始字符串转换为输出的最佳方法是什么?您可以轻松获得单独的设置(播放器,移动,详细信息)?

2 个答案:

答案 0 :(得分:2)

这将解析字符串并将变量放在地图中:

    Map<String,String> vars = new HashMap<>();
    String input = "SVR GAME MOVE {PLAYER: \"PLAYER\", MOVE: \"1\", DETAILS: \"\"}";
    Pattern pattern = Pattern.compile("([A-Za-z]+): \"([^\"]*)\"");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        vars.put(matcher.group(1), matcher.group(2));
    }

答案 1 :(得分:0)

使用jackson library,您可以执行以下操作:

String input = "{PLAYER: \"PLAYER\", MOVE: \"1\", DETAILS: \"\"}";

ObjectMapper mapper = new ObjectMapper();
JsonNode yourJson = mapper.readTree(input);
System.out.println(yourJson.get("PLAYER"));
System.out.println(yourJson.get("MOVE"));
System.out.println(yourJson.get("DETAILS"));