C# 将JSON反序列化为.net对象
我在将JSON反序列化到对象时遇到问题。我读了几个答案,但没有一个对我有帮助。C# 将JSON反序列化为.net对象,c#,json,C#,Json,我在将JSON反序列化到对象时遇到问题。我读了几个答案,但没有一个对我有帮助。 这是我的JSON文件: { "meta": { "status": 200, "msg": "OK" }, "response": { "blog": { "title": "title", "name": "name", "url": "url" } } } 这是我的班级:
这是我的JSON文件:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "title",
"name": "name",
"url": "url"
}
}
}
这是我的班级:
public class TextInfo
{
public class Meta
{
public int status { get; set; }
public string msg { get; set; }
}
public class Blog
{
public string title { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Response
{
public Blog blog { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
}
现在,我尝试像这样反序列化json,但我不知道如何操作数据:
TextInfo txt = JsonConvert.DeserializeObject<TextInfo>(json);
TextInfo txt=JsonConvert.DeserializeObject(json);
你能帮我弄清楚吗?提前感谢。唯一的区别是TextInfo应该包含元和响应:
public class TextInfo
{
public Meta meta { get; set; }
public Response response { get; set; }
}
public class Meta
{
public int status { get; set; }
public string msg { get; set; }
}
public class Blog
{
public string title { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Response
{
public Blog blog { get; set; }
}
你像你说的那样反序列化:
TextInfo txt = JsonConvert.DeserializeObject<TextInfo>(json);
TextInfo txt=JsonConvert.DeserializeObject(json);
三件事:
var txt=JsonConvert.DeserializeObject(JSONstr)代码>
public class Meta
{
public int status { get; set; }
public string msg { get; set; }
}
public class Response
{
public Blog blog { get; set; }
}
public class Blog
{
public string title { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class TextInfo
{
public Meta meta { get; set; }
public Response response { get; set; }
}
您的
TextInfo
类中没有任何要反序列化的属性。它只声明另一个类。
根据您的源代码,您应该反序列化到RootObject
。这将返回一个带有meta
和response
属性的实例。
然后您将访问它们:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.meta.msg);
rootobjectobj=JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.meta.msg);
但我不知道如何操作数据这意味着什么?例如,我想在数据库中存储博客名,我不知道如何从“txt”中获取博客名,你的意思是textInfo.response.Blog.name
?注意:您应该使用.NET命名约定,而您目前没有使用。属性应该是PascalCase。