簡體   English   中英

使用Gson對JSON進行反序列化

[英]Deserialization of a JSON using Gson

我正在從服務器接收類似於以下語法的JSON,我需要一些反序列化和解析的幫助。 我對此進行了大量閱讀,發現使用GSON非常有用! (我將在此處發布對我的代碼的所有更新)

(更正的JSON):

    [{
    "name" : "Zone1",
    "types" : [{"datatype":"string","brand":"string","index":0},
            {"datatype":"string","value":"int32,"index":1},
            {"datatype":"string","url":"string,"index":2}]
    "data" : [["gucci",2,"www.whoami12345.com"]]
   },
   {
   "name" : "Zone2",
   "types" : [{"datatype":"string","brand":"string","index":0},
            {"datatype":"string","value":"int32,"index":1},
            {"datatype":"string","url":"string,"index":2}]
   "data" : [["nike", 23,"www.nike.com"]]
  }]

我發現該站點Link非常簡潔,因為它解釋了如何使用gson並很好地說明了反序列化。 我對JSON的理解是它是一個數組,而數據字段是一個Arrays數組。

我的問題是我該如何解析? 我有一個函數,它將使用字符串搜索特定的區域名稱。 反序列化發生並且條目匹配正確的區域后,應該返回數據類型和URL。 從那篇文章中,我的理解是我應該使用JSONArray。 對於任何反饋,我們都表示感謝。 下面是我已經開始的一些代碼

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

String name;    

public class data{
    String brand;
    int num;
    int url;
 }

public class types{
    String datatype;
    int value;
    String url;
}


public types Deserialiser(String json, String zone){ // this is the json string that will be passed into the function


JsonObject jsonObject = json.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray();
int index = -1;
for (int i = 0; i<jsonArray.size();i++){
   String temp = jsonArray.get(i).get("name");
   if (temp.equals(zone){
      index =i;
      break;
   }

}

....

types jsonTypes = new types();
// set everything else
return jsonTypes;
}

有效的JSON(我認為):

[{"name"  : "Zone1",
   "types" : ["datatype":"string","value":"int","url":"string"],
   "data"  : [["gucci",2,"www.whoami12345.com"]]},
  {"name"  : "Zone2",
   "types" : ["datatype":"string","value":"int","url":"string"],
   "data"  : [["nike", 23,"www.nike.com"]]}
]

否-缺少“對象”括號

再試一次:

[{"name"  : "Zone1",
   "types" : [{"datatype":"string","value":"int","url":"string"}],
   "data"  : [["gucci",2,"www.whoami12345.com"]]},
  {"name"  : "Zone2",
   "types" : [{"datatype":"string","value":"int","url":"string"}],
   "data"  : [["nike", 23,"www.nike.com"]]}
]

啊!! 好多了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM