EsotericSoftware / jsonbeans

Java object graphs, to and from JSON automatically
BSD 3-Clause "New" or "Revised" License
91 stars 30 forks source link

Array deserializing issue/needs update from libgdx? #11

Closed ghost closed 10 years ago

ghost commented 10 years ago

It looks like this project is out of date compared to the libgdx version. The following bug occurs when using this code but does not occur with the libgdx version. (See class comment for bug description.)

//import com.badlogic.gdx.utils.Json;
import com.esotericsoftware.jsonbeans.Json;

/**
 * Bug: Deserializing an array of objects with length other than 1
 * fails in some cases. The deserializer creates an array whose length
 * is based on jsonData.size, but this value is 1 (see Json.java:851).
 * It then tries to populate the array with the correct number of objects
 * by iterating over the children. This results in an
 * ArrayIndexOutOfBoundsException after the first child since the array
 * has the wrong length.
 * 
 * @author Christopher G. Jennings
 */
public class JsonArrayBug {
    public static class Contents {
        public String innerDummy;
    }

    public static class Container {
        public String outerDummy;
        public Contents[] innerArray;
    }

    public static void main( String[] args ) {
        for( int i=0; i<3; ++i ) {
            try {
                System.out.printf( "Trying inner array of size %d\n", i );
                thereAndBackAgain( i );
            } catch( Throwable t ) {
                t.printStackTrace();
            }
        }
    }

    private static void thereAndBackAgain( int arraySize ) throws Throwable {
        Container c = new Container();
        c.innerArray = new Contents[ arraySize ];
        for( int i=0; i<c.innerArray.length; ++i ) {
            c.innerArray[i] = new Contents();
        }
        Json json = new Json();
        String j = json.toJson( c );
        Container reconstructed = json.fromJson( Container.class, j );      
    }
}
ThanosFisherman commented 8 years ago

Hey. I'm not opening a new issue as I'm not having any problems with the current version but are you planning on keep updating this lib? I use it extensively on my Android apps.

NathanSweet commented 8 years ago

I use it in my projects as well, so yes, I will continue maintaining it. It hasn't needed any new features for quite some time.

FWIW, JsonValue also isn't the most efficient way of doing it, though it is an easy to use API (which was the goal). Using JsonReader and overriding the protected methods enables streaming JSON parsing.

ThanosFisherman commented 8 years ago

Cool thanks for letting me know