简体   繁体   English

Newsoft json反序列化密钥作为值

[英]Newsoft json deserialize key as a value

How would i got about deserializing key from a json string as a value of an object? 我将如何从json字符串反序列化键作为对象的值?

Example: 例:

{"vals": {"foo":{"val":1}, "bar":{"val":1}}}

Into 进入

public Bizz
{
   public IList<Buzz> vals;
}
public Buzz
{
  public string name;
  public int val;
}

Where name would hold foo/bar . 名称存放foo/bar

You can either write your custom Json Converter or you can simplify your Json a bit and go with Dictionary<> instead of Buzz . 您可以编写自定义的Json Converter,也可以简化Json并使用Dictionary<>而不是Buzz Is the Json generated by you? Json是由您生成的吗?

To be able to convert to Dictionary<> , the Json should look like 为了能够转换为Dictionary<> ,Json应该看起来像

{"foo":"1", "bar":"1"}

As a previous poster said, it naturally serialize it to a dictionary, say serialized , and then you can do: 正如先前的海报所说,它自然地将其序列化为字典,例如serialized ,然后您可以执行以下操作:

var bizzes = new Bizz 
{
    vals = serialized
        .Select(kvp => new Buzz { name = kvp.Key, val = kvp.Value.val})
        .ToList()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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