C# 使用 Json.NET 反序列化键值对数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15789539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:58:21  来源:igfitidea点击:

Deserialize array of key value pairs using Json.NET

c#json.netdeserialization

提问by pbz

Given the following json:

鉴于以下json:

[ {"id":"123", ... "data":[{"key1":"val1"}, {"key2":"val2"}], ...}, ... ]

that is part of a bigger tree, how can I deserialize the "data" property into:

那是更大树的一部分,如何将“数据”属性反序列化为:

List<MyCustomClass> Data { get; set; }

or

或者

List<KeyValuePair> Data { get; set; }

or

或者

Dictionary<string, string> Data { get; set; }

using Json.NET? Either version will do (I prefer List of MyCustomClass though). I already have a class that contains other properties, like this:

使用 Json.NET?任何一个版本都可以(不过我更喜欢 MyCustomClass 列表)。我已经有一个包含其他属性的类,如下所示:

public class SomeData
{
   [JsonProperty("_id")]
   public string Id { get; set; }
   ...
   public List<MyCustomClass> Data { get; set; }
}

where "MyCustomClass" would include just two properties (Key and Value). I noticed there is a KeyValuePairConverter class that sounds like it would do what I need, but I wasn't able to find an example on how to use it. Thanks.

其中“MyCustomClass”将只包含两个属性(键和值)。我注意到有一个 KeyValuePairConverter 类,听起来它可以满足我的需要,但我无法找到有关如何使用它的示例。谢谢。

回答by Boo

The simplest way is deserialize array of key-value pairs to IDictionary<string, string>:

最简单的方法是将键值对数组反序列化为IDictionary<string, string>


public class SomeData
{
    public string Id { get; set; }

    public IEnumerable<IDictionary<string, string>> Data { get; set; }
}

private static void Main(string[] args)
{
    var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";

    var obj = JsonConvert.DeserializeObject<SomeData>(json);
}

But if you need deserialize that to your own class, it can be looks like that:

但是如果你需要将它反序列化到你自己的类中,它看起来像这样:


public class SomeData2
{
    public string Id { get; set; }

    public List<SomeDataPair> Data { get; set; }
}

public class SomeDataPair
{
    public string Key { get; set; }

    public string Value { get; set; }
}

private static void Main(string[] args)
{
    var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";

    var rawObj = JObject.Parse(json);

    var obj2 = new SomeData2
    {
        Id = (string)rawObj["id"],
        Data = new List<SomeDataPair>()
    };

    foreach (var item in rawObj["data"])
    {
        foreach (var prop in item)
        {
            var property = prop as JProperty;

            if (property != null)
            {
                obj2.Data.Add(new SomeDataPair() { Key = property.Name, Value = property.Value.ToString() });
            }

        }
    }
}

See that I khow that Valueis stringand i call ToString()method, there can be another complex class.

看到我知道那Valuestring我调用的ToString()方法,可能还有另一个复杂的类。

回答by pbz

I ended up doing this:

我最终这样做了:

[JsonConverter(typeof(MyCustomClassConverter))]
public class MyCustomClass
{
  internal class MyCustomClassConverter : JsonConverter
  {
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
      JObject jObject = JObject.Load(reader);

      foreach (var prop in jObject)
      {
        return new MyCustomClass { Key = prop.Key, Value = prop.Value.ToString() };
      }

      return null;
    }

    public override bool CanConvert(Type objectType)
    {
      return typeof(MyCustomClass).IsAssignableFrom(objectType);
    }
  }

  public string Key { get; set; }
  public string Value { get; set; }
}

回答by saber tabatabaee yazdi

public class Datum
{
    public string key1 { get; set; }
    public string key2 { get; set; }
}

public class RootObject
{
    public string id { get; set; }
    public List<Datum> data { get; set; }
}

i used this wizard as well json2csharp.comto generate class for deserialized

我也使用这个向导json2csharp.com来生成反序列化的类

for using that

使用那个

using RestSharp;
using Newtonsoft.Json;

IRestResponse restSharp= callRestGetMethodby_restSharp(api_server_url);
string jsonString= restSharp.Content;

RootObject rootObj= JsonConvert.DeserializeObject<RootObject>(jsonString);
return Json(rootObj);

if you call rest by restsharp

如果你通过restsharp调用rest

    public IRestResponse callRestGetMethodby_restSharp(string API_URL)
    {
        var client = new RestSharp.RestClient(API_URL);
        var request = new RestRequest(Method.GET);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("cache-control", "no-cache");
        IRestResponse response = client.Execute(request);
        return response;
    }

also you can get this 6 line of restsharp from getpostman.comtools

您也可以从getpostman.com工具中获得这 6 行restsharp