简体   繁体   中英

serialize json to object c#

I am new to json,I am trying to convert json response to object

the json is

"[{\"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:

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.

Replace it with List<List<string>> fields instead.

It is an issue with the Json not being a match with the objects you have. If you want the JSON to match your C# models it would look like this:

[
    {
        "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/

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.

I work with JSON and Web-based APIs regularly and will never use anything else in C# to handle JSON conversions.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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