【问题标题】:Json how to get value from key with special character - json-simpleJson如何从具有特殊字符的键中获取值 - json-simple
【发布时间】:2013-04-21 00:45:46
【问题描述】:

我无法从键中获取值,因为键中包含 $。这是jsonobject:

JSONParser parser = new JSONParser();
String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";
JSONObject obj = (JSONObject)parser.parse(str);

String oid = (String) obj.get("$oid");
System.out.println("oid: " + oid);

但是输出是:

oid: null

如何处理带有特殊字符$ 的键?

【问题讨论】:

    标签: java json parsing json-simple


    【解决方案1】:

    字符串str 的格式不正确。您需要转义引号。试试这个:

    String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";
    

    【讨论】:

    • 对不起。实际上它有效。得到错误的 json 对象是我的错误。谢谢
    【解决方案2】:

    这行得通。但我没有使用 JSONParser。

        String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";
        JSONObject obj;
        try 
        {
            obj = new JSONObject(str);
            String oid = (String) obj.get("$oid");
            System.out.println("oid: " + oid);
            Toast.makeText(this, oid, Toast.LENGTH_SHORT).show();
    
        } 
        catch (JSONException e) {
            e.printStackTrace();
        }
    

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 2011-07-29
      相关资源
      最近更新 更多