在C#中将字符串转换为对象
问题描述:
我有一个字符串,形式为
"{value: "some"}"
(通过序列化对象获得,但属性名称上不带引号)或
"{"value": "some"}"
I have a string in the form of
"{value: "some"}"
(Obtained by serializing object but without quotes on the property name) OR
"{"value": "some"}"
我希望将其转换为对象(类似于新的{value = "some"}
)
而不是JObject {"value" = "some"}
I wish to convert it a object (Similar to new {value = "some"}
)
And not JObject {"value" = "some"}
有帮助吗?
答
检查此处获取有关使用Json.NET反序列化匿名类型的信息.
Check here for info on deserializing anonymous types using Json.NET.
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
Console.WriteLine(customer2.Name);
// Mike