如何将json对象反序列化为类

时间:2015-02-19 22:43:20

标签: c# json json.net json-deserialization

我有以下json字符串:

    private const string Json = @"{
        'responseMessage': '',
        'response': 'PASS',
        'responseData': {
            'user': {
            'initials': 'XXX',
            'name': 'XXXX XXXX',
            'companies': [
                '0002',
                '0007',
                '0022',
                '0033',
                '9999'
            ],
            'employee': 'XXXX'
            }
        },
        'responseFor': 'myCommand'
    }'";

我的ServerResponse类看起来像这样:

[JsonObject(MemberSerialization.OptIn)]
public class ServerResponse
{
    [JsonProperty("responseFor")]
    public string ResponseFor { get; set; }

    [JsonProperty("responseData")]
    public string ResponseData { get; set; }

    [JsonProperty("response")]
    public string Response { get; set; }

    [JsonProperty("responseMessage")]
    public string ResponseMessage { get; set; }
}

我叫这个命令:

var serverResponse = JsonConvert.DeserializeObject<ServerResponse>(Json);

我希望这会填充我的serverResponse对象,但我得到了这个例外:

{Newtonsoft.Json.JsonReaderException: Error reading string. Unexpected token: StartObject. Path 'responseData', line 4, position 30.
  at Newtonsoft.Json.JsonReader.ReadAsStringInternal () [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonTextReader.ReadAsString () [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonContract contract, Boolean hasConverter) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id) [0x00000] in <filename unknown>:0 }

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要一个ResponseData类才能使序列化工作,因为json中的值不是字符串。您还需要一个用户。

创建看起来像这样的响应数据和用户类。

[JsonObject(MemberSerialization.OptIn)]
public class User
{
     [JsonProperty("initials")]
     public string Initials { get; set; }

     [JsonProperty("name")]
     public string Name { get; set; }

     [JsonProperty("companies")]
     public string[] Companies { get; set; }

     [JsonProperty("responseMessage")]
     public string ResponseMessage { get; set; }
}

[JsonObject(MemberSerialization.OptIn)]
public class ResponseData
{
     [JsonProperty("user")]
     public User User { get; set; }

     [JsonProperty("employee")]
     public string Employee { get; set; }
}

然后在ServerResponse类中,更改ResponseData以使用此ResponseData类。