我从 GXT 开始,对如何使用 JsonReader 解析具有多个根对象的有效 json 字符串有点困惑。我有一组选择框来构建 sql 语句以在网格中显示记录。我也从数据库中获取选择的值。我正在尝试做的是对我的 php 数据库函数的单个请求,以使用一个字符串中的选择框的所有值构建 json。我的第一个想法是 JsonReader。
这是我正在使用的 json 示例:
"categories":[{"id":"1","value":"categoryValue1"},{"id":"2","value":"categoryValue2"}], "frequencies":[{"id":"1","value":"frequencyValue1"},{"id":"2","value":"frequencyValue2"}]
以api中的 cityList 示例为基础,这就是我到目前为止所得到的。
JsonRootObject 接口:
public interface JsonRootObject {
List<SelectionProperties> getCategories();
List<SelectionProperties> getFrequencies();
}
JsonRootObjectAutoBeanFactory:
public interface JsonRootObjectAutoBeanFactory extends AutoBeanFactory {
AutoBean<JsonRootObject> jsonRootObject();
}
我创建了一个 SelectionProperties 接口,因为它们都是单个 int/string 值对:
public interface SelectionProperties {
String getId();
String getValue();
}
现在,根据api:
// To convert from JSON data, extend a JsonReader and override
// createReturnData to return the desired type.
所以我为类别和频率创建了一个阅读器;分类阅读器:
public class CategoryReader
extends
JsonReader<ListLoadResult<SelectionProperties>, JsonRootObject> {
public CategoriesReader(AutoBeanFactory factory, Class<JsonRootObject> rootBeanType) {
super(factory, rootBeanType);
}
protected ListLoadResult<SelectionProperties> createReturnData(Object loadConfig, JsonRootObject incomingData) {
return new ListLoadResultBean<SelectionProperties>(incomingData.getCategories());
}
}
频率阅读器:
public class FrequencyReader extends
JsonReader<ListLoadResult<SelectionProperties>, net.apoplectic.testapps.client.JsonRootObject> {
public FrequencyReader(AutoBeanFactory factory, Class<JsonRootObject> rootBeanType) {
super(factory, rootBeanType);
}
protected ListLoadResult<SelectionProperties> createReturnData(Object loadConfig, JsonRootObject incomingData) {
return new ListLoadResultBean<SelectionProperties>(incomingData.getFrequencies());
}
}
这感觉不太对劲。我正在创建基本相同代码的多个实例并两次解析实际的 json 字符串(此时。一旦我深入研究,我可能有更多的网格选项)。我的问题是我遗漏了什么还是有更有效的方法来解析响应字符串?从我的 onSuccessfulResponse:
JsonRootObjectAutoBeanFactory factory = GWT.create(JsonRootObjectAutoBeanFactory.class);
CategoryReader catReader = new CategoriesReader(factory, JsonRootObject.class);
FrequencyReader freqReader = new FrequenciesReader(factory, JsonRootObject.class);
categories = catReader.read(null, response);
frequencies = freqReader.read(null, response);
List<SelectionProperties> categoriesList = categories.getData();
List<SelectionProperties> frequenciesList = frequencies.getData();
ListBox cateBox = new ListBox(false);
ListBox freqBox = new ListBox(false);
for (SelectionProperties category : categoriesList )
{
cateBox.addItem(category.getValue(), category.getId());
}
for (SelectionProperties frequency : frequenciesList)
{
freqBox.addItem(frequency.getValue(), frequency.getId());
}
以上确实有效,两个 ListBox 都正确填充。我只是想知道这是否是正确的方法。提前致谢!