Java Gson解析泛型类型的Json对象
我已将以下json写入一个文件,我希望通过Gson读取该文件:Java Gson解析泛型类型的Json对象,java,unit-testing,gson,Java,Unit Testing,Gson,我已将以下json写入一个文件,我希望通过Gson读取该文件: { "identifier": "CONFIG", "data": [ { "identifier": "HOTKEY", "data": { "hotKey": "testKey1", "type": "APPLICATION", "runnableContext": "testContext1" } }, {
{
"identifier": "CONFIG",
"data": [
{
"identifier": "HOTKEY",
"data": {
"hotKey": "testKey1",
"type": "APPLICATION",
"runnableContext": "testContext1"
}
},
{
"identifier": "HOTKEY",
"data": {
"hotKey": "testKey2",
"type": "APPLICATION",
"runnableContext": "testContext2"
}
}
]
}
在上面的Json中,您可以看到标识符和数据构造是递归重复的。因此,表示此重复模式的基本类是一个泛型类,如下所示:
{
"identifier": "CONFIG",
"data": {
}
}
此模式由JsonData类表示,如下所示:
import java.util.Set;
....
import com.google.common.collect.ImmutableSet;
/**
* Class representing a simple {@link JsonData#identifier},
* {@link JsonData#data} format. This class can be used to
* persist application data for example in a Configuration file.
*
* @author SW029693
* @since v1.0
*/
public class JsonData <T>{
/**
* Represents a unique identifier
*/
private String identifier;
/**
* Represents the data pertaining to this {@link JsonData#identifier}
*/
private T data;
private static final Set<String> VALID_JSON_ID_TYPES = ImmutableSet.of("CONFIG","HOTKEYS","HOTKEY","RECOMMENDATIONS");
public JsonData(String identifier, T data) {
super();
this.identifier = identifier;
this.data = data;
}
/**
* Getter for {@link JsonData#identifier}
* @return
*/
public String getIdentifier() {
return identifier;
}
/**
* Sets the {@link JsonData#identifier} to the given value
* @param identifier
* Represents a unique {@link JsonData#identifier}
* @throws VerifyException
* If the argument is {@code null} or {@code empty}
*/
public void setIdentifier(String identifier) throws VerifyException{
Verifier.verifyNotNull(identifier, "identifier : null");
Verifier.verifyNotEmpty(identifier,"identifier : empty");
this.identifier = identifier;
}
/**
* Getter for {@link JsonData}
* @return
*/
public T getData() {
return data;
}
/**
* Sets the {@link JsonData#data} to the given value
* @param identifier
* Represents a unique {@link JsonData#data}
* @throws VerifyException
* If the argument is {@code null}
*/
public void setData(T data) {
Verifier.verifyNotNull(data, "data : null");
this.data = data;
}
@Override
public String toString() {
return "JsonData [identifier=" + identifier + ", data=" + data + "]";
}
}
由以下人员成功读取:
private static JsonData<ConfigurationProperty> readconfigFile() {
Reader reader = null;
JsonData<ConfigurationProperty> data = null;
Gson gson = null;
Type confType;
try {
reader = new FileReader("./config.json");
gson = new GsonBuilder().create();
confType = new TypeToken<JsonData<ConfigurationProperty>>() {}.getType();
data = gson.fromJson(reader,confType);
} catch (FileNotFoundException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage()); }
finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage());
}
}
return data;
}
private静态JsonData readconfigFile(){
Reader=null;
JsonData数据=null;
Gson-Gson=null;
类型转换类型;
试一试{
reader=newfilereader(“./config.json”);
gson=new GsonBuilder().create();
confType=newTypeToken(){}.getType();
data=gson.fromJson(reader,confType);
}catch(filenotfounde异常){
e、 printStackTrace();
失败(“读取config.json文件时测试失败:+e.getMessage());}
最后{
试一试{
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
失败(“读取config.json文件时测试失败:+e.getMessage());
}
}
返回数据;
}
但是如果你看第一个json,这是JsonData的递归结构。在解析时,我还需要告诉Gson第一个数据对象是一个JsonData对象数组。我还需要告诉gson,该数组中的每个JSONData对象都是ConfigurationProperty类型
我不知道怎么做。我想出来了。我就是这样做的
private static JsonData<List<ConfigurationProperty>> readconfigFileList() {
Reader reader = null;
JsonData<List<ConfigurationProperty>> dataArray = null;
Gson gson = null;
Type confType;
Type confTypeArray;
try {
reader = new FileReader("./config.json");
gson = new GsonBuilder().create();
confType = new TypeToken<JsonData<List<ConfigurationProperty>>>() {}.getType();
dataArray = gson.fromJson(reader,confType);
System.out.println(dataArray.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage()); }
finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage());
}
}
return dataArray;
}
private静态JsonData readconfigFileList(){
Reader=null;
jsondatadataarray=null;
Gson-Gson=null;
类型转换类型;
类型数组;
试一试{
reader=newfilereader(“./config.json”);
gson=new GsonBuilder().create();
confType=newTypeToken(){}.getType();
dataArray=gson.fromJson(reader,confType);
System.out.println(dataArray.toString());
}catch(filenotfounde异常){
e、 printStackTrace();
失败(“读取config.json文件时测试失败:+e.getMessage());}
最后{
试一试{
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
失败(“读取config.json文件时测试失败:+e.getMessage());
}
}
返回数据数组;
}
使用Gson库查找以下用于通用Json对象解析或未知Json对象解析的代码
public class JsonParsing {
static JsonParser parser = new JsonParser();
public static HashMap<String, Object> createHashMapFromJsonString(String json) {
JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
HashMap<String, Object> map = new HashMap<String, Object>();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
if (null != value) {
if (!value.isJsonPrimitive()) {
if (value.isJsonObject()) {
map.put(key, createHashMapFromJsonString(value.toString()));
} else if (value.isJsonArray() && value.toString().contains(":")) {
List<HashMap<String, Object>> list = new ArrayList<>();
JsonArray array = value.getAsJsonArray();
if (null != array) {
for (JsonElement element : array) {
list.add(createHashMapFromJsonString(element.toString()));
}
map.put(key, list);
}
} else if (value.isJsonArray() && !value.toString().contains(":")) {
map.put(key, value.getAsJsonArray());
}
} else {
map.put(key, value.getAsString());
}
}
}
return map;
}
}
公共类JsonParsing{
静态JsonParser=新JsonParser();
公共静态HashMap createHashMapFromJsonString(字符串json){
JsonObject object=(JsonObject)parser.parse(json);
Set=object.entrySet();
迭代器迭代器=set.Iterator();
HashMap=newHashMap();
while(iterator.hasNext()){
Map.Entry=iterator.next();
String key=entry.getKey();
JsonElement value=entry.getValue();
if(null!=值){
如果(!value.isJsonPrimitive()){
if(value.isJsonObject()){
put(key,createHashMapFromJsonString(value.toString());
}else if(value.isJsonArray()&&value.toString()包含(“:”){
列表=新的ArrayList();
JsonArray数组=value.getAsJsonArray();
if(null!=数组){
for(JsonElement元素:数组){
add(createHashMapFromJsonString(element.toString());
}
地图。放置(键、列表);
}
}else if(value.isJsonArray()&&!value.toString()包含(“:”){
put(key,value.getAsJsonArray());
}
}否则{
put(key,value.getAsString());
}
}
}
返回图;
}
}
~z~钱德拉
private static JsonData<List<ConfigurationProperty>> readconfigFileList() {
Reader reader = null;
JsonData<List<ConfigurationProperty>> dataArray = null;
Gson gson = null;
Type confType;
Type confTypeArray;
try {
reader = new FileReader("./config.json");
gson = new GsonBuilder().create();
confType = new TypeToken<JsonData<List<ConfigurationProperty>>>() {}.getType();
dataArray = gson.fromJson(reader,confType);
System.out.println(dataArray.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage()); }
finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage());
}
}
return dataArray;
}
public class JsonParsing {
static JsonParser parser = new JsonParser();
public static HashMap<String, Object> createHashMapFromJsonString(String json) {
JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
HashMap<String, Object> map = new HashMap<String, Object>();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
if (null != value) {
if (!value.isJsonPrimitive()) {
if (value.isJsonObject()) {
map.put(key, createHashMapFromJsonString(value.toString()));
} else if (value.isJsonArray() && value.toString().contains(":")) {
List<HashMap<String, Object>> list = new ArrayList<>();
JsonArray array = value.getAsJsonArray();
if (null != array) {
for (JsonElement element : array) {
list.add(createHashMapFromJsonString(element.toString()));
}
map.put(key, list);
}
} else if (value.isJsonArray() && !value.toString().contains(":")) {
map.put(key, value.getAsJsonArray());
}
} else {
map.put(key, value.getAsString());
}
}
}
return map;
}
}