简体   繁体   中英

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:

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

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 .

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.

You need to escape the " character inside the ProductName string and you have a extra comma at the end.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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