stleary / JSON-java

A reference implementation of a JSON package in Java.
http://stleary.github.io/JSON-java/index.html
Other
4.54k stars 2.56k forks source link

Allow type widening (eg integer to string) #842

Closed FloEberle closed 11 months ago

FloEberle commented 11 months ago

Hello 👋

I was wondering if in an upcoming version type widening would be possible or made configurable.

Assume in this example XML we expect the value of the <root>-Element always to be returned as type "string", even if there is a numeric value in it.

At least I was confused by the public interface of "getString"

Best regards

        // works because value is a string
        final JSONObject jsonObject = XML.toJSONObject("<root>foo</root>");
        System.out.println(jsonObject.getString("root"));

        // does not work because value is not recognized as a string
        final JSONObject jsonObject2 = XML.toJSONObject("<root>1337</root>");
        System.out.println(jsonObject2.getString("root"));

        //Workaround
        final JSONObject jsonObject3 = XML.toJSONObject("<root>1337</root>");
        System.out.println(String.valueOf(jsonObject3.opt("root")));
FloEberle commented 11 months ago

never mind, i found the parameter i was looking for just now 🤦 sorry

keepStrings – If true, then values will not be coerced into boolean or numeric values and will instead be left as strings