0

I have a JSON as shown below

{
    "qty": "1",
    "dswer": 0,
    "bag": {
        "dm": "2",
        "rate": "---",
        "ghy": "3013-04-05T00:00:00.000-05:00",
        "dee": "301304",
        "desc": "SSAA APR 05 2013 --- BGG"
    }
}

My requirement is that if the rate attribute in above Json is --- then treat it that as as InValid Request .

I dont want to assign this JSON to a Java class , for various reasons

So i was trying this way

package com;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String args[]) {


        String str = "{\r\n" + 
                "    \"qty\": \"1\",\r\n" + 
                "    \"dswer\": 0,\r\n" + 
                "    \"bag\": {\r\n" + 
                "        \"dm\": \"2\",\r\n" + 
                "        \"rate\": \"---\",\r\n" + 
                "        \"ghy\": \"3013-04-05T00:00:00.000-05:00\",\r\n" + 
                "        \"dee\": \"301304\",\r\n" + 
                "        \"desc\": \"SSAA APR 05 2013 --- CALL\"\r\n" + 
                "    }\r\n" + 
                "}";

        if(str.contains("rate:---"))
        {
            System.out.println("InValid");
        }
        else
        {
            System.out.println("Valid");
        }


    }

}

But its always displaying as Valid .

Please tell me how to solve this ??

Thanks

2 Answers 2

3
if(str.contains("rate:---")) // is false because
if(str.contains("\"rate\": \"---\"")) // would be true
Sign up to request clarification or add additional context in comments.

Comments

2

Your if condition needs to be this:-

if(str.contains("\"rate\": \"---\""))

Since in your JSON, both rate & --- are enclosed within double-quotes, you need to add those in your if condition by escaping those.

Even though this would work, I strongly recommend you parse your JSON properly using either org.json.JSONObject or com.google.gson.JsonObject.

Comments

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.