For a project we are working with a telnet server where we receive our data from. After a line is read from a telnet connection i get the following string:
Original string:
SVR GAME MOVE {PLAYER: "PLAYER", MOVE: "1", DETAILS: ""}
I'm trying to convert this to an output I can easily use without too many exploitability occuring. The desired format would be to easily get(PLAYER) or get. I tried using regex in combination with json see the code below:
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();
}
The problem is when the details are empty this would result in a Unexpected token RIGHT BRACE(}). Furthermore when players take exploitative name for example quotes in their names the code will crash easily.
What is the best way to convert the original String to an output where you can get the seperate settings easily(player,move,details)?
,then you can again split at:{and the last}and consider that your json String. Parse it with your Json parsing library (because REGEX is not appropriate for nested properties)