0

In my below code, colData stores JSON String. Sample example for colData-

{"lv":[{"v":{"tenureSiteReg":null,"bghtItms":48,"pnlValue":105.478409,"byrSgmnt":2,"cstmrId":"814296998","slrRevRnk":-99.0,"soldItms":0,"slrSgmnt":6,"byrRevRnk":0.013,"mainAcct":78,"gmv":0.0,"cstmrRevRnk":0.021,"pnlRev":313.438843,"cstmrSgmnt":51,"gmb":4674.76,"totalVal":142.536293,"userId":493},"cn":42}],"lmd":20130}

Now I am trying to match id value with userId value in the above JSON String. Meaning if id value is 493 then in the above JSON String userId value should also be 493. And in the JSON String, it might be possible there are lot of userId values so all the userId values should be matching with id. If any of them doesn't matches then log the exception.

So I was trying something like this-

private static final Pattern USER_ID_PATTERN = Pattern.compile("userId:\\d+");

for (String str : colData) {
    Matcher matcher = USER_ID_PATTERN.matcher(str);

        while (matcher.find()) {
            if (!matcher.group().equals("userId:"+id))
                 System.out.println("LOG exception");

            }
}

But for the above JSON String, it is not going inside while loop also. Is there anything I am missing?

5
  • 4
    Is there anything I am missing? A JSON parser, perhaps? Commented Mar 3, 2013 at 1:12
  • @HotLicks, Can you provide me the example as well to achieve the above scenario? Commented Mar 3, 2013 at 1:21
  • Parse the JSON into a map. In the map locate the "lv" array of maps. Iterate through the array and locate the "v" element, which is another map. Inside that map locate the "userId" element. Commented Mar 3, 2013 at 2:12
  • Where does the id value come from? Is it a separate string or is it supposed to be in the JSON? Commented Mar 3, 2013 at 6:20
  • Yes it's a separate string. Commented Mar 3, 2013 at 17:50

2 Answers 2

2

Like Hot Lips noted in the comments, you should really use a JSON processor for this.

Here's a rudimentary example using the Jackson JSON Processor. I assumed that id is a separate string since I didn't see it in the JSON.

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;

class Test {
    public static void main(String[] args) {
        String json = "{\"lv\":[{\"v\":{\"tenureSiteReg\":null,\"bghtItms\":48," +
                "\"pnlValue\":105.478409,\"byrSgmnt\":2,\"cstmrId\":\"814296998\",\"slrRevRnk\":-99.0," +
                "\"soldItms\":0,\"slrSgmnt\":6,\"byrRevRnk\":0.013,\"mainAcct\":78,\"gmv\":0.0," +
                "\"cstmrRevRnk\":0.021,\"pnlRev\":313.438843,\"cstmrSgmnt\":51,\"gmb\":4674.76," +
                "\"totalVal\":142.536293,\"userId\":493},\"cn\":42}],\"lmd\":20130}";
        String id = "493";

        ObjectMapper mapper = new ObjectMapper();

        try {
            JsonNode rootNode = mapper.readTree(json);
            List<JsonNode> userIds = rootNode.findValues("userId");         
            for (JsonNode node : userIds)
            {
                if (!id.equals(node.toString())) {
                    System.out.println("Log exception: id "+id+" != userId "+node);
                    break;
                } else {
                    System.out.println("Congratulations! id "+id+" = userId "+node);
                }               
            }
        } catch (JsonProcessingException e) {
            System.out.println("JsonProcessingException: ");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IOException: ");
            e.printStackTrace();
        }
    }
}

Running this class produces:

Congratulations! id 493 = userId 493
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Daniel for the help. I did exactly as it is. But I am getting error at readTree method saying that The method readTree(JsonParser) in the type ObjectMapper is not applicable for the arguments (String). May be I imported wrong jar file that's why? Can you please point me to right jar files if that is the case. I downloaded the jars from here.
@Nevzz03 - I'm using version 1.9 and I'm using Maven to handle my dependencies. If you're using Maven, you can point to this repo: repository.codehaus.org/org/codehaus/jackson. Otherwise, you should be able to get all of the jars from wiki.fasterxml.com/JacksonDownload#Latest_stable_1.x_version. My project has the following 4 jars on the classpath: jackson-core-asl-1.9.2.jar; jackson-mapper-asl-1.9.2.jar; jackson-jaxrs-1.9.2.jar; jackson-xc-1.9.2.jar
0

Maybe you are simply missing the double quotation mark?

"userId:"493

try this for the pattern:

"userId\":(\\d+)"

Similarly you need the \" inside the matcher.group().equals(..)

3 Comments

Still the same thing. I tried using this- public static final Pattern USER_ID_PATTERN = Pattern.compile("userId:\"(\\d+)");. It's not going inside the while loop
oh my bad, the double quotation mark was in the wrong position relative to the colon. here is the corrected pattern: try it again. "userId\":(\\d+)"
This pattern was verified as correct. If you want to use json parser instead it's your call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.