Retrofit을 사용한 동적 키 Json 문자열 해석
동적 키 Json String을 구문 분석하려고 합니다.
"report":{
"data":{
"results":{
"558952cca6d73d7d81c2eb9d":{
"Max":-1,
"Min":-1,
"Slope":-1,
},
"558ce148a6d73d7d81c2fa8a":{
"Max":-2,
"Min":-1,
"Slope":-2,
}
}
}
}
Following: 데이터를 가져오려고 하는데 마지막 동적 json 문자열을 구문 분석하는 동안 오류가 발생했습니다.
public class Report {
@SerializedName("data")
@Expose
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
@Override
public String toString() {
return "Report{" +
"data=" + data +
'}';
}
}
public class Data {
@SerializedName("results")
@Expose
private ResultInside result;
public ResultInside getResult() {
return result;
}
public void setResult(ResultInside result) {
this.result = result;
}
}
public class ResultInside {
/*@SerializedName("results")
@Expose*/
private Map<String, Vitals> elemDetails = new HashMap<>();
public Map<String, Vitals> getElemDetails() {
return elemDetails;
}
public void setElemDetails(Map<String, Vitals> elemDetails) {
this.elemDetails = elemDetails;
}
}
이 경우의 해석 방법 제안!
당신의.resultInside
클래스가 JSON에 존재하지 않는 오브젝트 계층을 추가하고 있습니다.맵을 이동해 보겠습니다.Data
학급results
들판.
public class Data {
@SerializedName("results")
@Expose
private Map<String, Vitals> result;
//....
}
이를 위한 더 나은 방법은 다음과 같습니다.
----------------------
public class Report {
@SerializedName("data")
@Expose
private Data data;
----------------------
public class Data {
public HashMap<String, DataValues> dataValues;
public Data() {
this.dataVaues = new HashMap<>();
}
}
-----------------------------
그런 다음 다음과 같은 파서 클래스를 만듭니다.
public class DataParser implements JsonDeserializer<Data> {
@Override
public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Data result = new Data();
try {
final HashMap<String, DataValues> map = readServiceUrlMap(json.getAsJsonObject());
if(map != null) {
result.dataValues = map;
}
}catch (JsonSyntaxException ex){
return null;
}
return result;
}
private HashMap<String, DataValues> readServiceUrlMap(final JsonObject jsonObject) throws JsonSyntaxException {
if(jsonObject == null) {
return null;
}
Gson gson = new Gson();
HashMap<String, DataValues> products = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
DataValues value = gson.fromJson(entry.getValue(), DataValues.class);
products.put(key, value);
}
return products;
}
----------------------------------------------
그런 다음 ApiClient 클래스에 이 값을 입력합니다.
public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if(retrofit == null) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Data.class, new DataParser());
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
.build();
이게 누군가에게 도움이 되었으면 좋겠다.
언급URL : https://stackoverflow.com/questions/33758601/parse-dynamic-key-json-string-using-retrofit
'programing' 카테고리의 다른 글
워드프레스의 각 카테고리에서 하나의 게시물만 받는 방법 (0) | 2023.02.23 |
---|---|
일치 문제를 사용한 regex에서의 Yup 유효성 검사 (0) | 2023.02.23 |
Docker 컨테이너의 Apache, PHP, WordPress 캐시 문제 (0) | 2023.02.23 |
때로는 Int 값, 때로는 String 값인 코드화 가능 사용 (0) | 2023.02.23 |
Ajax, 클릭 시 다중 요청 방지 (0) | 2023.02.23 |