2014-03-04 71 views
-1

这里是我的类反序列化复杂的字符串

class Respondents 
{ 
    public string ID { get; set; } 
    public string version { get; set; } 
    public string Status { get; set; } 
    public int Seed { get; set; } 
    public string Start { get; set; } 
    public string End { get; set; } 
    public string Duration { get; set; } 
    public Dictionary<string, string[]> Answers { get; set; } 

    public Respondents() 
    { 
     Answers = new Dictionary<string, string[]>(); 
    }  
} 

和IM尝试使用下面的代码 - 反序列化它:

string jsonResp = File.ReadAllText(@"D:\JsonOutputFiles\Sample Survey.json"); 
      obj = JsonConvert.DeserializeObject<Respondents>(jsonResp); 

我不能做it.Need你的意见和建议

+0

什么是你可能遇到的问题? – Ian

+1

你可以发布JSON文本吗?当你说不能做到这一点时,你会得到一个错误吗?如果是这样,它是什么? – BuddhiP

+0

{ “ID”: “Resp1”, “版本”: “版本”, “状态”: “部分”, “种子”:1, “开始”: “日期时间”, “结束”: “日期时间”, “持续时间”: “秒”, “答案”:{ “Q1”:{ “值”: “[email protected]” }, “Q2”:{ “值” :20 }, “Q3”:{ “值”:空 }, “Q4”:{ “值”: “5” }, “Q5”:{ “值”:100 }, “Q6”:{ “值”:[ “3”, “4” ] }, “Q7”:{ “值”:空 }, “Q8”:{ “值”:[ “4”, “5”, “8” ] }, “Q9”:{ “值”:空 } } } –

回答

0

您的json的问题是Value可能包含int,stringstring array。即使你采用其他答案中所说的动态方式,在使用之前应检查该值(无论是否为阵列)。

我会写一个JSON转换器,以及所有的值转换为List<string>

var obj = JsonConvert.DeserializeObject<Respondents>(jsonResp); 

public class Val 
{ 
    [JsonConverter(typeof(StringArrayConverter))] 
    public List<string> Value { set; get; } 
} 

public class Respondents 
{ 
    public string ID { get; set; } 
    public string Version { get; set; } 
    public string Status { get; set; } 
    public int Seed { get; set; } 
    public string Start { get; set; } 
    public string End { get; set; } 
    public string Duration { get; set; } 
    public Dictionary<string,Val> Answers { get; set; } 
} 

public class StringArrayConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     throw new NotImplementedException(); 
    } 

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) 
    { 
     if (reader.ValueType == typeof(long)) 
     { 
      return new List<string>() { reader.Value.ToString() }; 
     } 

     if (reader.ValueType == typeof(string)) 
     { 
      return new List<string>() { (string)reader.Value }; 
     } 
     return serializer.Deserialize<List<string>>(reader); 
    } 

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

谢谢。问候 –

+0

@AakashDhoundiyal如果您打算使用任何这些答案,请阅读此http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

+0

另一种可以帮助的方法是让您的类与DataMember属性绑定在一些私有字段上,这些属性是对象,然后使用公共属性的get accessor测试逻辑来判断它是字符串,整数,字符串[]等类型 –

0

为什么不使用动态类型来反序列化它呢?

​​

我不认为你输入JSON适合在运行一个C#模型由于正在应用的“答案”字典的“阵列”式按键 - 例如, Q1,Q2,Q3

此外,我通常会在我的类上使用DataContract属性,并在我的成员上使用DataMember属性来指示需要序列化。