Jarobusa
Jarobusa

Reputation: 19

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

Upvotes: 1

Views: 212

Answers (3)

Jon Crawley
Jon Crawley

Reputation: 81

Gson shouldn't do this by default, it should escape the " with a \ for you, If you datatype for ProductName is not a straight string this could be part of your problem when the object is serialized.

Upvotes: 0

Stephen
Stephen

Reputation: 19944

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

Upvotes: 3

P. Galbraith
P. Galbraith

Reputation: 2527

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/

Upvotes: 2

Related Questions