2013-04-29 63 views
0

我有一个JSON如下图所示的Java:从JSON格式

{ 
    "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" 
    } 
} 

我要求确认在Java中值是,如果在上面的JSON是速率属性---然后把它作为无效请求。

我不想这个JSON分配到一个Java类,由于种种原因

所以我试图这样

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"); 
     } 


    } 

} 

但它总是显示为有效。

请告诉我如何解决这个问题?

感谢

回答

3
if(str.contains("rate:---")) // is false because 
if(str.contains("\"rate\": \"---\"")) // would be true 
2

if条件必须是这样的: -

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

由于您JSON,两者rate & ---是双引号括起来,你需要添加那些您的if条件通过逃脱那些。

即使这可行,我强烈建议您使用org.json.JSONObjectcom.google.gson.JsonObject正确解析您的JSON。