我在尝试读取下面的json值时遇到意外的解析错误。这是我在调用外部API后得到的响应
"{
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
}
}"
我想从字符串中获取上面json中的booking_id。
这是我在线生成的模型
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);
答案 0 :(得分: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 :(得分:1)
我认为它无效,我认为这是因为booking_id
和status
。 booking_id
和status
的数据属性不是字符串,因此我认为这是问题所在。你应该把它作为字符串(带引号)传递:
"{
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"
}
}"
希望它有所帮助!
答案 2 :(得分: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_id
和status
周围的引文。
这个有效的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;