簡體   English   中英

使用Gson解析無鍵的嵌套JSON對象

[英]Parsing nested JSON objects without keys using Gson

我有一個包含以下內容的JSON:

[ {
    "lines" : {
        "0" : "Hammersmith & City",
        "1" : "Circle"
    },
    "id" : "233",
    "name" : "Shepherd's Bush Market"
}, {
    "lines" :"",
    "id" : "233",
    "name" : "Shepherd's Bush Market"
}, {
    "lines" : {
        "0" : "Hammersmith & City",
        "1" : "Circle"
    },
    "id" : "233",
    "name" : "Shepherd's Bush Market"
},
, {
    "lines" : "",
    "id" : "233",
    "name" : "Shepherd's Bush Market"
  }]

通常,我可以創建一個這樣的對象

public class MyObject {

    public String id;  
    public String name;
    public Line[] lines;

    public class Line {
        public String key;
        public String value;
    }
}

Gson序列化程序將處理解析,但是在這種情況下, lines沒有任何鍵/ ID。 我嘗試使用HashMapsMaps而不是內部類,但是它不起作用。 有什么方法可以使用Gson解析嗎?

更新:

我已將linesMyObject更改為Map<String, String> ,並向JSON響應中添加了更多行

目前,這是我用來解析JSON的代碼

Type listType = new TypeToken<List<MyObject>>(){}.getType();
List<MyObject> data = getGson().fromJson(str, listType);

Caused by: com.google.gson.JsonParseException: The JsonDeserializer MapTypeAdapter    failed to deserialize json object "" given the type java.util.Map<java.lang.String, java.lang.String>

瀏覽完整個JSON響應后,似乎lines不可用時以空String (“”)的形式返回,而當行不存在時以地圖的形式返回。 我認為這可能是問題的一部分

使用Map<String, String>代替Line[] lines

(您不需要Class Line

它應該工作。

或者,如果您的鍵是整數Map<Integer, String>也可以工作

[編輯]

您的json字符串表示對象列表: {..},{..},{..}

您需要使用[]包裝。

因此,工作的json應該是:

[
    {
        "lines": {
            "0": "Hammersmith & City",
            "1": "Circle"
        },
        "id": "233",
        "name": "Shepherd's Bush Market"
    },
    {
        "lines": {
            "0": "Hammersmith & City",
            "1": "Circle"
        },
        "id": "233",
        "name": "Shepherd's Bush Market"
    },
    {
        "lines": {
            "0": "Hammersmith & City",
            "1": "Circle"
        },
        "id": "233",
        "name": "Shepherd's Bush Market"
    }
]

為MyObject

public class MyObject {
 public String id;

 public String name;

 public Map<String,String> lines;   
}

主要方法

    Gson gson = new Gson();
    Type type = new TypeToken<List<MyObject>>(){}.getType();
    List<MyObject > objList = gson.fromJson(str, type);


    assert(objList != null);  // validate not null

    for(MyObject obj : objList){

        System.out.println("id=" + obj.id + "; name=" + obj.name);
    }

輸出:

id=233; name=Shepherd's Bush Market
id=233; name=Shepherd's Bush Market
id=233; name=Shepherd's Bush Market

在循環中,您也可以提取Map

我喜歡Maxim的簡單解決方案,並喜歡+1。 Bur還有另外一種更復雜的方法。 Lines類中,您可以將鍵寫為_0_1

class Lines {
    private String _0;
    private String _1;
    //@Override
    //public String toString() {
    //    return "Lines [0=" + _0 + ", 1=" + _1 + "]";
    //}

}

並像這樣在MyObject使用它

class MyObject {

    private Lines lines;
    private String id;
    private String name;

    //@Override
    //public String toString() {
    //    return "Example [lines=" + lines + ", id=" + id + ", name=" + name + "]";
    //}
}

此后,您將必須創建將從數字鍵中刪除_ FieldNamingStrategy

class MyNameStrategy implements FieldNamingStrategy {

    static Pattern numericPattern = Pattern.compile("_\\d+");

    @Override
    public String translateName(Field f) {
        if (numericPattern.matcher(f.getName()).matches()){
            return f.getName().substring(1);
        }else{
            return f.getName();
        }
    }
}

要使用此策略,您需要通過GsonBuilder創建Gson

Gson gson = new GsonBuilder().setFieldNamingStrategy(
        new MyNameStrategy()).create();
//...
MyObject[] arr = gson.fromJson(jsonString, MyObject[].class);
System.out.println(Arrays.toString(arr));

您也很正確,您的JSon在"lines" : ""有問題。 由於您將object{...}內的數據)放置在那里,因此以后無法將格式更改為string (不是JSon格式的對象)。
因此,如果您可以更改JSon,則應將"lines" : ""替換為

  • "lines" : null
  • "lines" : {}

暫無
暫無

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

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