简体   繁体   English

如何将JSON解析为ActiveJDBC模型?

[英]How to parse JSON into an ActiveJDBC Model?

I am using ActiveJDBC for a pet project. 我正在使用ActiveJDBC进行宠物项目。 I cannot seem to find a way to convert a JSON array into List nor Java array. 我似乎找不到将JSON数组转换为List或Java数组的方法。 The code below does take the JSON array and creates a list, BUT the model is not populated. 下面的代码确实采用JSON数组并创建一个列表,但未填充模型。 Meaning, number.get("winning_numbers") is null when I expect it to hold a value. 意思是,当我希望它保持一个值时, number.get("winning_numbers")null

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. 我知道ActiveJDBC需要仪器,我确保发生这种情况,因此我怀疑这是问题所在。

# 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. 违规行在第二个缩进if语句内。 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 编辑模型 - 简单地作为ActiveJDBC文档中的示例

public class Draw extends Model {
}

Your model has no property methods, so Gson is not setting any values (I assume that it uses standard JavaBeans property name conventions). 您的模型没有属性方法,因此Gson不设置任何值(我假设它使用标准的JavaBeans属性名称约定)。 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. 由于Gson的工作原理,你可能想尝试使用方法名称: set_winning_numberssetWinning_NumberssetWinning_numbers - 我不确定。 However, currently you have no methods for Gson to match. 但是,目前你没有Gson匹配的方法。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM