Question

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 :)

Was it helpful?

Solution

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).

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top