2017-03-17 78 views
0

嘗試讀取下面的JSON價值。我得到意想不到的語法錯誤是響應我調用外部API意外的解析錯誤JSON C#

"{ 
status: 201, 
data: { 
    booking_id: B2B-E51771039A176C, 
    booking_amount: 5398.00, 
    room_charges: 5398.00, 
    meal_charges: 0.00, 
    inclusion_charges: 600.00, 
    taxes: 1133.58, 
    status: Initiated 
} 
}" 

後得到我想從該booking_id上面的json在一個字符串中。

下面是我在網上產生

public class Data 
    { 
     [JsonProperty("booking_id")] 
     public string booking_id { get; set; } 
     [JsonProperty("booking_amount")] 
     public string booking_amount { get; set; } 
     [JsonProperty("room_charges")] 
     public string room_charges { get; set; } 
     [JsonProperty("meal_charges")] 
     public string meal_charges { get; set; } 
     [JsonProperty("inclusion_charges")] 
     public string inclusion_charges { get; set; } 
     [JsonProperty("taxes")] 
     public string taxes { get; set; } 
     [JsonProperty("status")] 
     public string status { get; set; } 
    } 

    public class RootObject 
    { 

     public int status { get; set; } 

     public Data data { get; set; } 
    } 

模型這是我用來轉換

RootObject rootobj=JsonConvert.DeserializeObject<RootObject>(JsonReplace); 
+1

如何你解析這個? –

+0

你還可以分享你用於反序列化的模型嗎? – mindOfAi

+0

請編輯您的問題以顯示您用於解析的代碼以及錯誤消息。 –

回答

1

這不是有效的JSON,因爲在JSON中,字符串值需要用引號引起來,否則將被視爲數字。在反序列化過程中,反序列化器會嘗試將數值視爲數字,並且會失敗。

這是有效的JSON:

{ 
    status: 201, 
    data: { 
      booking_id: "B2B-E51771039A176C", 
      booking_amount: 5398.00, 
      room_charges: 5398.00, 
      meal_charges: 0.00, 
      inclusion_charges: 600.00, 
      taxes: 1133.58, 
      status:"Initiated" 
    } 
} 

通知各地booking_idstatus報價。

這有效的JSON都會有這樣一類:

public class Data 
{ 
    public string booking_id { get; set; } 
    public double booking_amount { get; set; } 
    public double room_charges { get; set; } 
    public double meal_charges { get; set; } 
    public double inclusion_charges { get; set; } 
    public double taxes { get; set; } 
    public string status { get; set; } 
} 

public class RootObject 
{ 
    public int status { get; set; } 
    public Data data { get; set; } 
} 

得到這樣的價值:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(json); 
var id = obj.data.booking_id; 
1

你JSON是無效的。 您的booking_id值應該包含雙引號和狀態文本中的字符串。

{ 
status: 201, 
data: { 
    booking_id: "B2B-E51771039A176C", 
    booking_amount: 5398.00, 
    room_charges: 5398.00, 
    meal_charges: 0.00, 
    inclusion_charges: 600.00, 
    taxes: 1133.58, 
    status: "Initiated" 
} 
} 
1

在我看來,它是無效的,我認爲這是因爲booking_idstatus的。 booking_idstatus的數據屬性不是字符串,所以我認爲這是問題所在。你應該通過它作爲字符串(帶引號):

"{ 
status: 201, 
data: { 
    booking_id: "B2B-E51771039A176C", 
    booking_amount: 5398.00, 
    room_charges: 5398.00, 
    meal_charges: 0.00, 
    inclusion_charges: 600.00, 
    taxes: 1133.58, 
    status: "Initiated" 
} 
}" 

希望它有幫助!

+0

是的,我得到的迴應是無效的,必須聯繫api提供商以正確的json格式給出有效的回覆。感謝:) – Melvin

+0

對你有好處。祝你的發展順利! :) – mindOfAi