Lovelyxredxpanda / json-simple

Automatically exported from code.google.com/p/json-simple
Apache License 2.0
0 stars 0 forks source link

arrays of java objects are not handled #28

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1.
        String a[] = { "first", "second" };
        String val=  JSONValue.toJSONString(a);
        System.out.println(JSONValue.toJSONString(a));

What is the expected output?
[ "first", "second" ]

What do you see instead?

[Ljava.lang.String;@13e8d89

Please provide any additional information below.

Arrays of all basic types mentioned in 
http://code.google.com/p/json-simple/wiki/MappingBetweenJSONAndJavaEntities 
should be handled too.

Additionally also arrays of basic java types (char, int, long) should be 
handled too.

Original issue reported on code.google.com by fano...@gmail.com on 1 Jul 2010 at 7:01

GoogleCodeExporter commented 9 years ago
Got it solved for me. Before calling JSONValue.toJSONString(o) I do this:

        if (o instanceof Object[])
            o=java.util.Arrays.asList((Object[])o);

and it works as expected for arrays of Strings. Still it would be nice to have 
similar code somewhere inside the library so such arrays inside other objects 
would work automatically.

Original comment by fano...@gmail.com on 1 Jul 2010 at 7:52

GoogleCodeExporter commented 9 years ago
The easy fix seems to be to add this line

                if(value instanceof Object[])
                        return JSONArray.toJSONString((List)java.util.Arrays.asList((Object[])value));

after line here
http://code.google.com/p/json-simple/source/browse/trunk/src/org/json/simple/JSO
NValue.java#149 and even nested java arrays inside lists or maps should work. 

This does not add too much overhead since java.util.Arrays.asList wraps array 
into ArrayList backed up by the very same array (so the array itself is not 
copied).

Original comment by fano...@gmail.com on 14 Jul 2010 at 11:54

GoogleCodeExporter commented 9 years ago
Sorry, in previous comment I meant this line 
http://code.google.com/p/json-simple/source/browse/tags/tag_release_1_1/src/org/
json/simple/JSONValue.java#204

But line 149 should be fixed in similar manner with toJSONString replaced by 
writeJSONString.

Original comment by fano...@gmail.com on 14 Jul 2010 at 12:13

GoogleCodeExporter commented 9 years ago

Original comment by fangyid...@gmail.com on 14 Jul 2010 at 1:10

GoogleCodeExporter commented 9 years ago

Original comment by fangyid...@gmail.com on 14 Jul 2010 at 1:14

GoogleCodeExporter commented 9 years ago
Oh, seems like I was reinventing the wheel. Totally missed issue #7 due to its 
generic name. Oh well, at least next person reporting this issue may find it 
easier :-)

Original comment by fano...@gmail.com on 14 Jul 2010 at 2:01