在C#中将Dictionary <string,object>转换为Dictionary <string,class>

时间:2018-02-04 09:17:31

标签: c# linq dictionary lambda

我有一个结构为的Jtoken。以下结构具有比下面更多的属性,但我只能使用以下结构

{{ "PersonId": 1234, "State": "Florida", "Gender": "Male", "Married ": 1, "SalaryUnderHundredDollar ": 1, }} 

我创建了一个类Person

public class Person
{
  public int PersonId {get;set;}
  public string State {get;set;}
  public string Gender {get;set;}
  public bool Married {get; set}
  public bool SalaryUnderHundredDollar {get;set}
}

我将上面的Jtoken转换为字典:

var dict = jtoken.First.ToObject<Dictionary<string, object>>().ToDictionary(x => x.Key, x => x.Value);

这将给出Person的所有属性,但我只想要上面的那些。现在我必须转换

     Dictionary<string,object> to Dictionary<string,class>

我正在做以下事情:

 var dict2= dict.Where(x => fieldsRequired.Contains(x.Key)).ToDictionary(x => x.Key, x => (Person)x.Value);

fieldsRequired是我需要的字符串字段列表,因为在Jtoken中有很多字段。

但是这种转换不起作用。

任何帮助?

1 个答案:

答案 0 :(得分:1)

将您的课程修改为:

public class Person
{
  public int PersonId {get;set;}
  public string State {get;set;}
  public string Gender {get;set;}
  public int Married {get; set}
  public int SalaryUnderHundredDollar {get;set}
}

然后使用:

var person = jtoken.First.ToObject<Person>();

问题是{J}中bool属性表示为01。因此,我们也将类中属性的类型更改为int

更好的选择是修复JSON以使truefalse代替01。另外,JSON用双花括号括起来很奇怪,"Married ""SalaryUnderHundredDollar "属性在末尾包含一个空格。这些问题也应该解决。

此外,您可以编写自定义JsonConverter,以便将值从01正确转换为bool。请参阅answer here

将建议放在一起并修复属性名称中的双花括号和空格会产生以下结果:

public class BoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((bool)value) ? 1 : 0);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value.ToString() == "1";
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool);
    }
}

public class Person
{
    public int PersonId { get; set; }
    public string State { get; set; }
    public string Gender { get; set; }
    [JsonConverter(typeof(BoolConverter))]
    public bool Married { get; set; }
    [JsonConverter(typeof(BoolConverter))]
    public bool SalaryUnderHundredDollar { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        string json =
            @"{ ""PersonId"": 1234, ""State"": ""Florida"", ""Gender"": ""Male"", ""Married"": 1, ""SalaryUnderHundredDollar"": 1 }";

        var jObject = JObject.Parse(json);
        var person = jObject.ToObject<Person>();
    }
}