简体   繁体   English

从javax.json.JsonArray转换为org.json.JSONArray

[英]Converting from javax.json.JsonArray to org.json.JSONArray

Is it possible to convert from the newer EJB JSON libraries to the older org.json ones without having to rely on org.json.simple or GSON? 是否可以从较新的EJB JSON库转换为较旧的org.json而不需要依赖org.json.simple或GSON?

In the case below, "buttons" is a populated JsonArray and I'm trying to copy it into a JSONArray for legacy code. 在以下情况下,“按钮”是一个填充的JsonArray,我正尝试将其复制到JSONArray中以获取旧代码。 But the initialization of JSONArray from a stringified value always fails with "A JSONObject text must begin with '{'" because a quote is seen as a first character rather than a curly brace. 但是,从字符串值初始化JSONArray始终失败,并显示“ JSONObject文本必须以'{'开头”,因为引号被视为第一个字符,而不是花括号。

JSONArray newButtons = new JSONArray(); for (int i = 0; i < buttons.size(); i++) { JsonString button = buttons.getJsonString(i); newButtons.put(new JSONArray(button.toString())); } return new JSONArray(newButtons);

It doesn't seem like there is any kind of org.json object that I can initialize from a string constructor with a toString() value from the javax.json library. 似乎没有可以从javax.json库中的toString()值从字符串构造函数初始化的org.json对象。 I have managed to move data from org.json structures to javax.json ones, but not vice versa. 我设法将数据从org.json结构移动到javax.json结构,但反之亦然。 Is the org.json library too inflexible to do this? org.json库是否太不灵活而无法做到这一点?

I haven't tried it, but I believe following should work. 我还没有尝试过,但是我相信下面的应该有用。

JSONArray newButtons = new JSONArray();
for (int i = 0; i < buttons.size(); i++) {
    JsonObject button = buttons.getJsonObject(i);
    newButtons.put(new org.json.JSONObject(button.toString()));
}
return newButtons;

With the following line you get first the object with index 'i' and then make a JSON String out of it. 在下面的代码行中,您首先获取索引为'i'的对象,然后使用该对象制作一个JSON字符串。 Your original code rather returns the element 'i' as a value instead of an object. 您的原始代码宁愿返回元素“ i”作为值而不是对象。

JsonString button = buttons.getJsonObject(i).toString();

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

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