简体   繁体   English

如何提取值中带有“(引号)”的JSON对象?(Java / GSon)

[英]How do I extract a JSON object that has a " (quote) in the value? (Java / GSon)

I am using gson to create Java objects and everything works great until I get the following: 我正在使用gson创建Java对象,并且一切正常,直到得到以下信息:

{
   "SkuID": "2040",
   "CheckDigit": "8",
   "StockNumber": "2040-8",
   "ProductName": "SalesReceiptBook(1)8"x4"(50)(3-PartNCR)",
   "YourCost": "4.45",
   "Points": "0.00",
   "IsKosher": "False"
},

GSon determines the " before the 8 as the end of the value and this stops GSon from further parsing and I get an invalid JSON error. GSon将8之前的"确定为值的结尾,这将阻止GSon进一步解析,并且我收到无效的JSON错误。

Thank you! 谢谢!

Robbie 罗比

The basic answer is to encode it properly. 基本答案是正确编码。 See the string diagram (4th) on http://www.json.org/ for how you're allowed to encode, or alternatively, validate your json at http://jsonlint.com . 有关如何编码的信息,请参见http://www.json.org/上的字符串图(第4个),或者在http://jsonlint.com上验证json。

Your string should be 您的字符串应该是

{
   "SkuID": "2040",
   "CheckDigit": "8",
   "StockNumber": "2040-8",
   "ProductName": "SalesReceiptBook(1)8\"x4\"(50)(3-PartNCR)",
   "YourCost": "4.45",
   "Points": "0.00",
   "IsKosher": "False"
}

The JSON you posted isn't valid. 您发布的JSON无效。

You need to escape the " character inside the ProductName string and you have a extra comma at the end. 您需要在ProductName字符串中转义“”字符,并在末尾添加一个逗号。

{
    "SkuID": "2040",
    "CheckDigit": "8",
    "StockNumber": "2040-8",
    "ProductName": "SalesReceiptBook(1)8\"x4\"(50)(3-PartNCR)",
    "YourCost": "4.45",
    "Points": "0.00",
    "IsKosher": "False"
}

In the future you can easily check if the JSON is valid using this online validator http://jsonlint.com/ 将来,您可以使用此在线验证器http://jsonlint.com/轻松检查JSON是否有效。

Gson默认情况下不应该这样做,它应该为您转义为\\,如果您的ProductName数据类型不是直字符串,则在序列化对象时可能会出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM