views:

269

answers:

2

OK, I am getting null for whatever reason I cannot fathom.

Here is my code:

import java.util.*;
import java.io.*;
import com.google.gson.*;


public class readGoogle {

    public static String MapTitle;
    public static Data data;
    public static Item item;
    public static String dan;
    public static FileReader fr;


        public static void main(String[] args) {

            /**
try {
    fr = new FileReader("map1.txt");
}catch(FileNotFoundException fne) {
    fne.printStackTrace();
}
        StringBuffer sb = new StringBuffer();
        char[] b = new char[1000];
        int n = 0;
        try {
        while ((n = fr.read(b)) > 0) {
             sb.append(b, 0, n);
         }
         }catch(IOException rex) {
             rex.printStackTrace();
         }
        String fileString = sb.toString();
        **/

                               String json =
                               "{"
                               +"'name': 'map_one.txt',"
                               +"'title': 'xxx One',"
                               +"'currentMap': 4,"
                               +"'rightMap': 3,"
                               +"'lefttMap': 5,"
                               +"'downMap': 1,"
                               +"'upMap': 2,"
                               +"'items': ["
                               +"   { name: 'Pickaxe', x: 5, y: 1 },"
                               +"   { name: 'Battleaxe', x: 2, y: 3 }"
                               +"],"
                               +"   'map': [ [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],"
                               +"   [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],"
                               +"   [ 1,7,1,1,1,24,1,1,24,1,1,1,1 ],"
                               +"   [ 1,7,1,1,7,1,1,1,24,1,1,1,1 ],"
                               +"   [ 1,7,7,7,1,24,24,24,24,1,1,1,1 ],"
                               +"   [ 1,1,7,1,1,24,1,24,1,1,1,1,1 ],"
                               +"   [ 1,1,1,1,1,24,1,1,1,1,1,1,1 ],"
                               +"   [ 1,1,3,1,1,24,1,1,1,1,1,1,1 ],"
                               +"   [ 1,3,3,1,1,24,1,1,1,1,1,1,1 ]]"
+"};";


    try {
    data = new Gson().fromJson(json, Data.class);
    }catch (Exception er) {
        er.printStackTrace();
    }

    System.out.println("Name of map: " + data.getTitle());
    System.out.println("File of map: " + data.getName());
    System.out.println("Current Map: " + data.getCurrentMap());
    System.out.println(data.getItems().get(0).getName()); // Pickaxe



    }

public class Item {
        public String name;
        public int x;
        public int y;

        public String getName() { return name; }
        public int getX() { return x; }
        public int getY() { return y; }

        public void setName(String name) { this.name = name; }
        public void setX(int x) { this.x = x; }
        public void setY(int y) { this.y = y; }
    }

      public static class Data {
            private String name;
            private String title;
            private int currentMap;
            private int leftMap;
            private int rightMap;
            private int upMap;
            private int downMap;
            private List<Item> items;
            private int[][] map;

            public String getName() { return name; }
            public String getTitle() { return title; }
            public int getCurrentMap() { return currentMap; }
            public int getUpMap() { return upMap; }
            public int getDownMap() { return downMap; }
            public int getLeftMap() { return leftMap; }
            public int getRightMap() { return rightMap; }
            public List<Item> getItems() { return items; }
            public int[][] getMap() { return map; }

            public void setName(String name) { this.name = name; }
            public void setTitle(String title) { this.title = title; }
            public void setCurrentMap(int currentMap) { this.currentMap = currentMap; }
            public void setItems(List<Item> items) { this.items = items; }
            public void setMap(int[][] map) { this.map = map; }
        }

}


public static class Item {
        public static String name;
        public static int x;
        public int y;

        public static String getName() { return name; }
        public static int getX() { return x; }
        public int getY() { return y; }

        public void setName(String name) { this.name = name; }
        public void setX(int x) { this.x = x; }
        public void setY(int y) { this.y = y; }
    }

      public static class Data {
            private String name;
            private String title;
            private int currentMap;
            private int leftMap;
            private int rightMap;
            private int upMap;
            private int downMap;
            private List<Item> items;
            private int[][] map;

            public String getName() { return name; }
            public String getTitle() { return title; }
            public int getCurrentMap() { return currentMap; }
            public int getUpMap() { return upMap; }
            public int getDownMap() { return downMap; }
            public int getLeftMap() { return leftMap; }
            public int getRightMap() { return rightMap; }
            public List<Item> getItems() { return items; }
            public int[][] getMap() { return map; }

            public void setName(String name) { this.name = name; }
            public void setTitle(String title) { this.title = title; }
            public void setCurrentMap(int currentMap) { this.currentMap = currentMap; }
            public void setItems(List<Item> items) { this.items = items; }
            public void setMap(int[][] map) { this.map = map; }
        }

}

Here is the output:

    com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.Default
TypeAdapters$CollectionTypeAdapter@6016a786 failed to deserialized json object [
{"name":"Pickaxe","x":5,"y":1},{"name":"Battleaxe","x":2,"y":3}] given the type
com.google.gson.ParameterizedTypeImpl@6c59096e
        at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDese
rializerExceptionWrapper.java:63)
        at com.google.gson.JsonDeserializationVisitor.invokeCustomDeserializer(J
sonDeserializationVisitor.java:88)
        at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCusto
mHandler(JsonObjectDeserializationVisitor.java:117)
        at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.j
ava:150)
        at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:123)
        at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(Json
DeserializationContextDefault.java:73)
        at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDes
erializationContextDefault.java:51)
        at com.google.gson.Gson.fromJson(Gson.java:495)
        at com.google.gson.Gson.fromJson(Gson.java:444)
        at com.google.gson.Gson.fromJson(Gson.java:396)
        at com.google.gson.Gson.fromJson(Gson.java:372)
        at readGoogle.main(readGoogle.java:62)
Caused by: java.lang.RuntimeException: No-args constructor for class readGoogle$
Item does not exist. Register an InstanceCreator with Gson for this type to fix
this problem.
        at com.google.gson.MappedObjectConstructor.constructWithNoArgConstructor
(MappedObjectConstructor.java:64)
        at com.google.gson.MappedObjectConstructor.construct(MappedObjectConstru
ctor.java:53)
        at com.google.gson.JsonObjectDeserializationVisitor.constructTarget(Json
ObjectDeserializationVisitor.java:41)
        at com.google.gson.JsonDeserializationVisitor.getTarget(JsonDeserializat
ionVisitor.java:56)
        at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:101)
        at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(Json
DeserializationContextDefault.java:73)
        at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDes
erializationContextDefault.java:51)
        at com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter.deserialize
(DefaultTypeAdapters.java:472)
        at com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter.deserialize
(DefaultTypeAdapters.java:435)
        at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDese
rializerExceptionWrapper.java:50)
        ... 11 more
Exception in thread "main" java.lang.NullPointerException
        at readGoogle.main(readGoogle.java:67)
Press any key to continue . . .

Something is wrong within the Items json array... :S

+3  A: 

are you sure the property 'name' of Item should be static? Doesn't seem right to me....

edit -- and the property 'x'

edit -- if you look at your stack trace, it says

Caused by: java.lang.RuntimeException: No-args constructor for class readGoogle$
Item does not exist.

So you need to provide a constructor that is public and takes no arguments.

hvgotcodes
Yep, neither of those should be `static`. Gson sets instance fields on objects... since there's no instance field for `name`, it's ignoring that when it reads the JSON.
ColinD
I removed all static from the Item method.. I get a new error. See original post.
Dan
i edited my answer....
hvgotcodes
Well folks! It's official I quit Java! Back to PHP/MySQL <_< Thanks for trying.
Dan
Weird, now it works. Hm....
Dan
Now time to find out how many items are in each array.. so for the 'item': would be 2!
Dan
@Dan: [`List` has a `size()` method](http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/util/List.html). Instead of ranting on Java, you'd better put some effort in learning basic Java. Follow the [Trails covering the basics](http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/). All is important, expect of Swing when you don't want to do UI development. Good luck.
BalusC
@hvgotcodes For the record, Gson doesn't require setters, getters or Serializable. It sets data directly on fields and what you do with them (exposing them with getters or not) is up to you. No arg constructor is required though.
ColinD
@BalusC, here's thing thing. I did. Then I lost it. So now I quit ;)
Dan
@Dan -- don't quit. come on man, this is basic stuff. once you get over the initial language hurtles you'll be rocking and rolling...
hvgotcodes
@ColinD -- editing my response for your feedback.
hvgotcodes
A: 

I had a similar problem and solved it by reading the documentation http://sites.google.com/site/gson/gson-user-guide on nested inner classes. You need to define your items class as a nested class of data and declare it as static, with an empty constructor.

John Barça