[英]Parse JSON number array using Gson
這是我要與Gson解析的JSON字符串。 我想快速簡單地解析它。
{
"values": [
[
1,
1,
0,
0,
0,
0,
11,
0.09090909090909091
],
[
[
0,
0,
0,
0,
0,
1,
0
],
[
0,
0,
0,
0,
0,
1,
0
],
[
0,
0,
0,
0,
0,
0,
0
],
[
0,
0,
0,
0,
0,
0,
0
],
[
0,
0,
0,
0,
0,
0,
0
],
[
0,
0,
0,
0,
0,
0,
0
],
[
0,
0,
0,
0,
0,
11,
0
],
[
0,
0,
0,
0,
0,
0.09090909090909091,
0
]
]
]
}
但是我不知道如何用Gson編寫解析代碼。 最好的結果是我是否可以從解析的對象中提取List。
我有可能寫這樣的課程嗎?
class Value
{
@SerializedName("0")
List<Float> value1;
@SerializedName("1")
List<Integer> value2;
...........
}
謝謝大家的幫助。
我知道這是最快的方式,它以最實用的格式為您獲取所需的信息。
您的JSON由包含list1(一個雙精度列表)和list2(一個雙精度列表列表)的列表組成。 假設您想完全解析所提供的示例,則這是一個可以使用的自包含類。
如果您需要有關其工作方式的詳細信息,請隨時詢問。
package stackoverflow.questions;
import java.lang.reflect.Type;
import java.util.List;
import stackoverflow.questions.Test.Wrapper;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
public class Q20118749 {
/**
* @param args
*/
public static void main(String[] args) {
String json = "{\"values\":[[1,1,0,0,0,0,11,0.09090909090909091],[[0,0,0,0,0,1,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,11,0],[0,0,0,0,0,0.09090909090909091,0]]]}";
JsonElement je = new JsonParser().parse(json);
JsonArray list = je.getAsJsonObject().get("values").getAsJsonArray(); // to get rid of the value part
Type listType1 = new TypeToken<List<Double>>() {}.getType();
Type listType2 = new TypeToken<List<List<Double>>>() {}.getType();
Gson g = new Gson();
List<Double> listOfDouble = g.fromJson(list.get(0), listType1);
List<List<Double>> listOfListOfDouble = g.fromJson(list.get(1), listType2);
System.out.println(listOfDouble);
System.out.println(listOfListOfDouble);
}
}
這是我的處決:
[1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 11.0, 0.09090909090909091]
[[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 11.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.09090909090909091, 0.0]]
當然,如果您的數據發生更改,則必須根據此代碼進行更改。
使用此代碼。
public class MyObject{
@SerializedName("values")
private Values[] mValues;
public Value[] getLoc() {
return mvalues;
}
}
public class Values{
@SerializedName("0")
private Zero[] mZero;
@SerializedName("1")
private One[] mOne;
public Zero[] getZero() {
return mZero;
}
public Value[] getOne() {
return mOne;
}
}
public class Zero{
@SerializedName("0")
private zint zero;
public int getZeroValue() {
return zero;
.........
}
}
像這樣你必須寫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.