在填充以下类型的Json时获取空的Java对象。
a.json:
------
{
"queries": [{
"query": {
"id": "q1",
"description": "Fire query to get the Auth token !!"
}
}
],
"executeQuery": ["q2", "q3"]
}
Query.java :
-----------
Note : @Data will take care of creating setter getter by Lombok library.
@Data
public class Query {
@Expose @SerializedName("id")
String id;
@Expose @SerializedName("description")
String description;
}
GRT.java :
----------
@Data
public class GRT{
@Expose @SerializedName("queries")
List<Query> queries ;
@Expose @SerializedName("executeQuery")
List<String> executeQuery;
}
Client call :
----------------------------------------------
private void readJson() throws IOException{
String fileName = "a.json";
// Get Gson object
Gson gson = newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
// read JSON file data as String
String fileData = new String(Files.readAllBytes(Paths.get(fileName)));
// parse json string to object
GenericRestTestDefinition grtDef = gson.fromJson(fileData, GenericRestTestDefinition.class);
System.out.println(grtDef.toString());
}
GRT(查询= [查询(id =空,描述=空)],executeQuery = [q2,q3])
不知道为什么不填充GRT->查询对象吗????
答案 0 :(得分:1)
正确的JSON如下所示。
{
"queries":
[
{"id":"q1","description":"Fire query to get the Auth token"},
{"id":"q2","description":"Fire query to get the Auth token 2"}
]
}
public class Test {
public static void main(String[] args) throws Exception {
readJson();
}
private static void readJson() throws IOException {
String json ="{\"queries\":[{\"id\":\"q1\",\"description\":\"Fire query to get the Auth token\"}]}";
// Get Gson object
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
GRT grt = new GRT();
grt.setQueries(Arrays.asList( new Query[]{new Query("q1", "Fire query to get the Auth token")} ));
System.out.println(gson.toJson(grt));
// parse json string to object
GRT grtDef = gson.fromJson(json, new TypeToken<GRT>(){}.getType());
System.out.println(grtDef.queries.get(0));
}
}
答案 1 :(得分:0)
如果您无法更改json文件格式,则可以使用以下模式:
@Data
public class GRT{
@Expose @SerializedName("queries")
private List<QueryWrapper> queries = new ArrayList<>();
public List<Query> getQueries() {
return queries.stream().map(it->it.query).collect(Collectors.toList());
}
@Expose @SerializedName("executeQuery")
List<String> executeQuery = new ArrayList<>();
}
@Data
public class QueryWrapper {
@Expose @SerializedName("query")
Query query;
}
@Data
public class Query {
public
@Expose @SerializedName("id")
String id;
@Expose @SerializedName("description")
String description;
}