How to Desrialize JSON using C#
I am currently using Json.Net to deserialize my JSON. I now have the following situation:
I am getting the following JSON response:
{"Success":false,"Errors":{"UserName":"User Name already registered","EmailAddress":"Email Address already registered"}}
I want to parse it into this type:
public class CustomJsonResult
{
public bool Success { get; set; }
public string[] Errors { get; set; }
}
Using Json.net, I tried doing this:
CustomJsonResult regResult = JsonConvert.DeserializeObject<CustomJsonResult>(json);
But this is not working, I get the error Cannot deserialize JSON obj开发者_如何转开发ect into type 'System.String[]'.
How can I fix this? (using Json.Net or any other library)
The problem is you're trying to convert a dictionary into an array. Try replacing your string[]
with Dictionary<string, string>
.
Errors
is not an array of string, it is an object
with UserName
and EmailAddress
as it's property.
{
"Success":false,
"Errors":{
"UserName":"User Name already registered",
"EmailAddress":"Email Address already registered"
}
}
well, you can create another class to store the error message
public CustomJsonError
{
public string UserName { get; set; }
public string EmailAddress { get; set; }
}
Then refactor the class
public class CustomJsonResult
{
public bool Success { get; set; }
public CustomJsonError Errors { get; set; } // I'm not sure if the property should be named as Errors
}
BTW, will error contain an array / list of errors?
Update
Well, you can use Dictionary<string, string>
(see other answer) or create a custom class for the Error. See http://james.newtonking.com/projects/json/help/SerializingCollections.html for serializing and deserializing Collection to and from JSON.
That's because your "Errors" in your JSON doesn't match what it's trying to deserialize to. It should be something like this:
public class CustomJsonResult
{
public bool Success { get; set; }
public ErrorType[] Errors { get; set; }
}
public class ErrorType
{
public string UserName {get;set;}
public string EmailAddress {get;set;}
}
If you want to change the JSON to match, it should look something like this:
{"Success":false, "Errors": ["User Name already registered", "Email Address already registered"]}
Otherwise you may need some intermediate mapping.
Using JavaScriptSerializer from standard .NET framework library System.Web.Extensions:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string,int>>("{ a: 1, b: 2 }");
Console.WriteLine(dict["a"]);
Console.WriteLine(dict["b"]);
Console.ReadLine();
}
}
}
精彩评论