-1

I'm using Gson to parse a JSON string like this:

{
 "key": 1b
}

However, when I parse this using JsonParser.parseString(), the value 1b is interpreted as the string "1b" instead of being parsed as a byte.

Here is the code I'm using:

JsonElement element = JsonParser.parseString(json);
System.out.println(element.getAsJsonObject().get("key")); // Outputs: "1b"

My expectation was that 1b would be parsed as a byte, similar to how 1 is parsed as a number. Is there a way to make Gson recognize 1b as a byte literal?

If not, what's the recommended way to parse such pseudo-JSON values that use Java-style type suffixes like b, s, l, etc.?

Thanks in advance!

asked Apr 12 at 2:53
1
  • 1
    1b is invalid JSON , Gson treats it as a string, not a byte. Either: Use valid JSON like "key": 1, or Post-process "1b" strings to parse manually. String raw = el.getAsJsonObject().get("key").getAsString(); byte b = Byte.parseByte(raw.replaceFirst("b$", "")); Commented Apr 12 at 3:04

1 Answer 1

1

The issue is not with Gson. JSON simply does not support numeric suffixes. In the JSON specifications (RFC 8259),

 Numeric values that cannot be represented in the grammar below (such
 as Infinity and NaN) are not permitted.
 number = [ minus ] int [ frac ] [ exp ]
 decimal-point = %x2E ; .
 digit1-9 = %x31-39 ; 1-9
 e = %x65 / %x45 ; e E
 exp = e [ minus / plus ] 1*DIGIT
 frac = decimal-point 1*DIGIT

Hence, Gson tries to interpret your data as a string. Since suffixes such as b, s, and l are not a JavaScript feature, you'll need to treat them as a string and parse it later.

answered Apr 12 at 2:59
Sign up to request clarification or add additional context in comments.

1 Comment

"you'll need to treat them as a string and parse it later" ... or stop trying to use JSON in a way that it wasn't designed to be used.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.