0

For some reasons I have to use a specific string in my project. This is the text file (it's a JSON File):

{"algorithm": 
[
    { "key": "onGapLeft", "value" : "moveLeft" },
    { "key": "onGapFront", "value" : "moveForward" },
    { "key": "onGapRight", "value" : "moveRight" },
    { "key": "default", "value" : "moveBackward" }
]
}

I've defined it in JAVA like this:

static String input = "{\"algorithm\": \n"+
"[ \n" +
    "{ \"key\": \"onGapLeft\", \"value\" : \"moveLeft\" }, \n" +
    "{ \"key\": \"onGapFront\", \"value\" : \"moveForward\" }, \n" +
    "{ \"key\": \"onGapRight\", \"value\" : \"moveRight\" }, \n" +
    "{ \"key\": \"default\", \"value\" : \"moveBackward\" } \n" +
"] \n" +
"}";

Now I have to isolate the keys and values in an array:

key[0] = onGapLeft; value[0] = moveLeft;
key[1] = onGapFront; value[1] = moveForward;
key[2] = onGapRight; value[2] = moveRight;
key[3] = default; value[3] = moveBackward;

I'm new to JAVA and don't understand the string class very well. Is there an easy way to get to that result? You would help me really!

Thanks!

UPDATE: I didn't explained it well enough, sorry. This program will run on a LEGO NXT Robot. JSON won't work there as I want it to so I have to interpret this JSON File as a normal STRING! Hope that explains what I want :)

Jonas Zimmer
  • 161
  • 2
  • 15
  • Welcome to Stackoverflow. If your input String is a JSON String then you should look at http://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java – Arnaud Denoyelle Sep 09 '13 at 16:52
  • Hey, thanks! JSON is unfortunatily no option because it's not running on my Lego NXT Robot. SO I have to interpret this JSON File as a string. I'm sorry I didn't explain that well enough! :) – Jonas Zimmer Sep 09 '13 at 17:10

2 Answers2

2

I propose a solution in several step.

1) Let's get the different parts of your ~JSON String. We will use a pattern to get the different {.*} parts :

public static void main(String[] args) throws Exception{
  List<String> lines = new ArrayList<String>();

  Pattern p = Pattern.compile("\\{.*\\}");
  Matcher matcher = p.matcher(input);
  while (matcher.find()) {
    lines.add(matcher.group());
  }
}

(you should take a look at Pattern and Matcher)

Now, lines contains 4 String :

{ "key": "onGapLeft", "value" : "moveLeft" }
{ "key": "onGapFront", "value" : "moveForward" }
{ "key": "onGapRight", "value" : "moveRight" }
{ "key": "default", "value" : "moveBackward" }

Given a String like one of those, you can remove curly brackets with a call to String#replaceAll();

List<String> cleanLines = new ArrayList<String>();
for(String line : lines) {
  //replace curly brackets with... nothing.
  //added a call to trim() in order to remove whitespace characters.
  cleanLines.add(line.replaceAll("[{}]","").trim());
}

(You should take a look at String String#replaceAll(String regex))

Now, cleanLines contains :

"key": "onGapLeft", "value" : "moveLeft"
"key": "onGapFront", "value" : "moveForward"
"key": "onGapRight", "value" : "moveRight"
"key": "default", "value" : "moveBackward"

2) Let's parse one of those lines :

Given a line like :

"key": "onGapLeft", "value" : "moveLeft"

You can split it on , character using String#split(). It will give you a String[] containing 2 elements :

//parts[0] = "key": "onGapLeft"
//parts[1] = "value" : "moveLeft"
String[] parts = line.split(",");

(You should take a look at String[] String#split(String regex))

Let's clean those parts (remove "") and assign them to some variables:

String keyStr = parts[0].replaceAll("\"","").trim(); //Now, key = key: onGapLeft
String valueStr = parts[1].replaceAll("\"","").trim();//Now, value = value : moveLeft

//Then, you split `key: onGapLeft` with character `:`
String key = keyStr.split(":")[1].trim();

//And the same for `value : moveLeft` : 
String value = valueStr.split(":")[1].trim();

That's it !

You should also take a look at Oracle's tutorial on regular expressions (This one is really important and you should invest time on it).

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • Thank you so much! This was my last attempt to get this program to work properly and you rescued me! :) (sadly I can't upvote this solution because I need 15 rep) – Jonas Zimmer Sep 09 '13 at 17:55
  • Just one more question! :) String[] parts = line.split(","); line is in your case a local String inside the for argument. Should that be cleanLines.Split(",")? – Jonas Zimmer Sep 09 '13 at 18:53
  • No :) cleanLines is a `String[]`. `String#split()` is only applicable to a `String`. You need to iterate on the `String[]` to work with lines one by one. – Arnaud Denoyelle Sep 09 '13 at 19:01
  • Oh my god.. I'm going crazy now. I don't want to bother you any longer but the robot does "not support regular expressions". I didn't know that, I learned it the hard way right now.. Is there any easy solution to modify your solution so it didn't use regular expressions? – Jonas Zimmer Sep 09 '13 at 20:37
  • Then you have 2 solutions : 1) You parse manually : use String.toCharArray() to convert your String to a char[] and interate on it. You should also be able to reimplement the split method without regex. 2) Some people developped some minimal JSON parser that you can include or copy-paste in your project : see http://eclipsesource.com/blogs/2013/04/18/minimal-json-parser-for-java/ – Arnaud Denoyelle Sep 09 '13 at 21:41
  • Thanks! I've implemented the split method now with NXT conform string operations. It's working now! You've been a great help! :) – Jonas Zimmer Sep 10 '13 at 00:19
0

You need to use a JSON parser library here. For example, with org.json you could parse it as

String input = "{\"algorithm\": \n"+
        "[ \n" +
            "{ \"key\": \"onGapLeft\", \"value\" : \"moveLeft\" }, \n" +
            "{ \"key\": \"onGapFront\", \"value\" : \"moveForward\" }, \n" +
            "{ \"key\": \"onGapRight\", \"value\" : \"moveRight\" }, \n" +
            "{ \"key\": \"default\", \"value\" : \"moveBackward\" } \n" +
        "] \n" +
        "}";

JSONObject root = new JSONObject(input);
JSONArray map = root.getJSONArray("algorithm");

for (int i = 0; i < map.length(); i++) {
    JSONObject entry = map.getJSONObject(i);
    System.out.println(entry.getString("key") + ": "
                          + entry.getString("value"));
}

Output :

onGapLeft: moveLeft
onGapFront: moveForward
onGapRight: moveRight
default: moveBackward
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
  • Hey, thanks! JSON is unfortunatily no option because it's not running on my Lego NXT Robot. SO I have to interpret this JSON File as a string. I'm sorry I didn't explain that well enough! :) – Jonas Zimmer Sep 09 '13 at 17:09