Search code examples
jsonjava-8gsonactivejdbcjavalite

How to parse JSON into an ActiveJDBC Model?


I am using ActiveJDBC for a pet project. I cannot seem to find a way to convert a JSON array into List nor Java array. The code below does take the JSON array and creates a list, BUT the model is not populated. Meaning, number.get("winning_numbers") is null when I expect it to hold a value.

Since there is no error I cannot find a way to populate that model, with the ultimate goal to persist it to the database. Any ideas?

I do know that ActiveJDBC requires instrumentation, and I have ensured that happens, therefore I doubt that's the problem.

# schema
create table draws (
  draw_date TIMESTAMP not null,
  winning_numbers varchar(20) not null,
  multiplier int not null,
  primary key (draw_date)
)

The offending line is within the second indented if statement. This is still prototype code, so apologies as I've yet to format it for code beautification.

# where the problem resides
public class PowerballLotteryService {
    private static final Logger log = LoggerFactory.getLogger(PowerballLotteryService.class);
    private static String LOTTO_URL = "http://data.ny.gov/resource/d6yy-54nr.json";

    public static List<LottoNumbers> getLatest() {
        List<LottoNumbers> latestNumbers = Lists.newArrayList();

        // rest client
        String result = null;
        List<Draw> numbersList = null;

        try {
            Client client = Client.create();
            WebResource webResource2 = client.resource(LOTTO_URL);
            ClientResponse response2 = webResource2.accept("application/json").get(ClientResponse.class);
            if (response2.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus());
            }

            result = response2.getEntity(String.class);

            if (result != null) {
                Gson gson = new GsonBuilder().create();
                numbersList = new Gson().fromJson(result, new TypeToken<List<Draw>>(){}.getType());

                if (numbersList != null) {
                    for(Draw number : numbersList) {
                        // This is always null for some reason: number.get("winning_numbers")
                        String winningNumber = number.get("winning_numbers").toString();
                        if (winningNumber != null) {
                            number.saveIt();
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return latestNumbers;
    }
}

EDIT The model - simple as the examples in ActiveJDBC docs

public class Draw extends Model {
}

Solution

  • Your model has no property methods, so Gson is not setting any values (I assume that it uses standard JavaBeans property name conventions). Something like this should work:

    public class Draw extends Model {
       public void setWinningNumbers(String n){ set("winning_numbers", n);}
    }
    

    Due to how Gson works, you might want to experiment with methods names: set_winning_numbers or setWinning_Numbers or setWinning_numbers - I'm not sure. However, currently you have no methods for Gson to match.

    Alternative solution: get data into maps:

    List<Map> numbersList = new Gson().fromJson(result, new TypeToken<List<Map>>(){}.getType());
    

    after that:

    List<Draw> draws = new ArrayList<>();
    for(Map m: numbersList){
        Draw d = new Draw();
        d.fromMap(m);
        draws.add(d);
    }