简体   繁体   English

将json序列化为对象c#

[英]serialize json to object c#

I am new to json,I am trying to convert json response to object我是 json 的新手,我正在尝试将 json 响应转换为对象

the json is json是

"[{\"fields\":[[\"name\",\"value\",\"values\",\"error\"],[\"username\",\"test\",null,\"\"],[\"password\",\"test\",null,\"\"],[\"accountid\",\"\",null,\"\"],[\"rememberMe\",\"Y\",null,\"\"],[\"language\",\"en-US\",null,\"\"],[\"S\",\"test\",null,null]],\"success\":\"Y\",\"message\":\"User authenticated. Logging in.\"}]"

I wrote two classes我写了两个类

  public class fields
    {
      public string name { get; set; }
      public string value { get; set; }
      public string values { get; set; }
      public string error { get; set; }
    }

    public class Demo
    {
        public List<fields> fields { get; set; }
        public string message { get; set; }
        public string success { get; set; }

    }

I made this Serialize code:我做了这个序列化代码:

JsonSerializer serializer = new JsonSerializer();
    Demo result = JsonConvert.DeserializeObject<Demo>(responseFromServer);

or this

  Demo result = new JavaScriptSerializer().Deserialize<Demo>(responseFromServer);

the error is错误是

Type '_Default+fields' is not supported for deserialization of an array

Thanks谢谢

Baaroz巴罗兹

I tried your code and it was a bit inconclusive for me.我试过你的代码,对我来说有点不确定。 But I can show you what i've found and you can try working from here:但是我可以向您展示我发现的内容,您可以尝试从这里工作:

First: As I commented on your question, the first and last character of your string are [ and ].第一:正如我对您的问题的评论,您的字符串的第一个和最后一个字符是 [ 和 ]。 That means your server is sending you an array.这意味着您的服务器正在向您发送一个数组。 To solve that, i just changed your deserialization line to this:为了解决这个问题,我只是将您的反序列化行更改为:

Demo[] result = new JavaScriptSerializer().Deserialize<Demo[]>(responseFromServer);

Second: The code was still having troubles to deserialize to your fields object, then I realized you were receiving an array of an array of strings, then I changed your property in the Demo class to this:第二:代码仍然无法反序列化到您的字段对象,然后我意识到您正在接收一个字符串数组的数组,然后我将您在 Demo 类中的属性更改为:

public string[][] fields { get; set; }

Hope this can help.希望这能有所帮助。

If you format your json string you will notice that each entry in fields contains another four entries, therefore List<fields> fields will not suffice.如果您格式化 json 字符串,您会注意到 fields 中的每个条目都包含另外四个条目,因此List<fields> fields不够的。

Replace it with List<List<string>> fields instead.将其替换为List<List<string>> fields

It is an issue with the Json not being a match with the objects you have. Json 与您拥有的对象不匹配是一个问题。 If you want the JSON to match your C# models it would look like this:如果您希望 JSON 与您的 C# 模型相匹配,它将如下所示:

[
    {
        "fields": [
            {
                "name": "Jeff",
                "value": "xcv",
                "values": "xcv",
                "error": "xcv"
            },
            {
                "name": "Jeff",
                "value": "xcv",
                "values": null,
                "error": null
            }
        ],
        "success": "Y",
        "message": "Userauthenticated.Loggingin."
    }
]

try using this site (there are many more like it) to play about with your C# & JSON till you get what you are after: http://json2csharp.com/尝试使用这个网站(还有更多类似的网站)来玩你的 C# 和 JSON,直到你得到你想要的: http : //json2csharp.com/

I'm pretty convinced Newtonsoft is literally the best possible way to do anything with JSON in C# and without any headaches, it's the most popular C# NuGet package in the world with almost 1 billion downloads, works in ALL .NET versions basically.我非常确信 Newtonsoft 是在 C# 中使用 JSON 做任何事情的最佳方式,而且没有任何麻烦,它是世界上最受欢迎的 C# NuGet 包,下载量接近 10 亿次,基本上适用于所有 .NET 版本。

I work with JSON and Web-based APIs regularly and will never use anything else in C# to handle JSON conversions.我经常使用 JSON 和基于 Web 的 API,并且永远不会使用 C# 中的任何其他东西来处理 JSON 转换。

Here's one of the simplest examples这是最简单的例子之一

string json_string = @"{
                  Firstname: ""Jane"",
                  Lastname: ""Doe"",
                  Age: 36,
                  IsEmployed: true,
                  IsMarried: true,
                  Children: 4
              }";
              
var person = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json_string);

Console.WriteLine(person.Forename);
Console.WriteLine(person.Lastname);
Console.WriteLine(person.Age);
Console.WriteLine(person.IsEmployed);
Console.WriteLine(person.IsMarried);
Console.WriteLine(person.Children);

It generates objects on the fly, no matter the structure!无论结构如何,它都会即时生成对象! Other solutions don't work in all .NET versions.其他解决方案不适用于所有 .NET 版本。

I wrote a simple, easy-to-follow article here https://turmanauli.medium.com/a-complete-guide-for-serializing-json-to-dynamic-objects-on-the-fly-in-c-7ab4799f648d about how to install and use Newtonsoft via NuGet Package Manager in your Visual Studio project.我在这里写了一篇简单易懂的文章https://turmanauli.medium.com/a-complete-guide-for-serializing-json-to-dynamic-objects-on-the-fly-in-c- 7ab4799f648d关于如何在 Visual Studio 项目中通过 NuGet 包管理器安装和使用 Newtonsoft。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM