如何让net.minidev.json.parser.JSONParser将000123123123解析为字符串而非数字
Got it, let's work through this problem with json-smart's JSONParser—the core issue here is that the parser is automatically coercing numeric-looking values with leading zeros into integer types, which strips those important leading zeros. Here's what you can do:
First, Check Your Input JSON
Wait a second—standard JSON doesn't allow numeric values with leading zeros (except for 0 itself). If your input JSON has something like {"number": 000123456789}, that's technically invalid JSON. The proper way to preserve leading zeros is to wrap the value in quotes to make it a string: {"number": "000123456789"}. If you can modify the input JSON to follow this standard, the parser will automatically keep it as a String without any extra configuration.
If You Can't Modify the Input JSON
If you're stuck with non-standard JSON that includes leading-zero numerics, you can adjust the parser's behavior to treat all numeric values as strings, which will preserve leading zeros. Use the USE_STRING_FOR_NUMBERS feature when initializing the parser:
import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import java.util.Map; public class LeadingZeroParseExample { public static void main(String[] args) throws ParseException { // Example non-standard JSON with leading-zero numeric String json = "{\"id\": 000123456789}"; // Initialize parser with USE_STRING_FOR_NUMBERS feature JSONParser parser = new JSONParser(JSONParser.Feature.USE_STRING_FOR_NUMBERS); Map<String, Object> parsedResult = (Map<String, Object>) parser.parse(json); // Now "id" will be a String with leading zeros intact String idValue = (String) parsedResult.get("id"); System.out.println(idValue); // Outputs: 000123456789 } }
Important Note
Keep in mind that this feature will convert all numeric values in your JSON to strings, not just those with leading zeros. If you need to preserve numeric types for other values while only converting leading-zero ones to strings, json-smart doesn't have a built-in feature for that. In that case, your best bet is to fix the input JSON to properly quote values that need leading zeros.
What If Your Input Already Has Quoted Strings?
If your JSON already wraps the value in quotes (like {"id": "000123456789"}) but you're still seeing it converted to a numeric type, double-check your downstream code. The parser should keep quoted values as strings by default—so the issue is likely in how you're handling the parsed Object later (e.g., accidental type conversion with utility methods).
内容的提问来源于stack exchange,提问作者Danilo Vasojević

