【问题标题】:how to Json Deserialize jsonstring [closed]如何 Json 反序列化 jsonstring [关闭]
【发布时间】:2022-01-14 15:00:32
【问题描述】:

我有一个返回的字符串看起来像这样

"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}"

我尝试使用字典进行反序列化,但仍未捕获数据。 最重要的数据只是在属性中命名,item1, item2

System.Text.Json.JsonSerializer.Deserialize<IDictionary<string, object>>(jsonString)

它给出了以下结果

 [0] [KeyValuePair]:{[properties, {"Item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"properties"
Value [object]:ValueKind = Object : "{"item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"lastModified"
[1] [KeyValuePair]:{[lastModified, 2021-12-09T19:00:12Z]}

【问题讨论】:

  • and it' giving the folowing result 那么实际的问题是什么?
  • 如何只捕捉名字? item1 和 item2 等进入字符串列表
  • 您可以通过提供您期望得到的示例来改进您的问题。从您所展示的内容来看,反序列化工作正常,但听起来您希望发生一些不同的事情。

标签: c# json-deserialization


【解决方案1】:

您可以按照以下简单步骤将 JSON 字符串反序列化为对象:

  1. 从 JSON 数据创建一个 C# 类。为此,请复制 JSON 字符串并转到 VS、编辑、选择性粘贴、将 JSON 粘贴为类。

如果成功,你会得到一个像这样的 C# 类

 public class Rootobject
{
    public Properties properties { get; set; }
    public DateTime lastModified { get; set; }
}

public class Properties
{
    public Item1 item1 { get; set; }
    public Item2 item2 { get; set; }
}

public class Item1
{
    public string dataType { get; set; }
}

public class Item2
{
    public string dataType { get; set; }
}

您可以将类重命名为对您有意义的任何内容。

你可以像这样反序列化

 var obj = JsonConvert.DeserializeObject<Rootobject>(
            "{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");

 Console.WriteLine(obj.properties.item2.dataType)// string

【讨论】:

    【解决方案2】:

    如果您只需要 dataType 属性的值而不需要整个对象,那么您可以使用 Linq to Json 来获取它,而无需反序列化和对象映射。

    例子:

    var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
    
    var fistItemDataTypeValue = (string)obj["properties"]?["item1"]["dataType"];
    
    var secondItemDataTypeValue = (string)obj["properties"]?["item2"]["dataType"];
    

    获取值作为字符串列表(注意:如果您已经知道 json 中的项目数):

        var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
    
        var listOfValues = new List<string>();
    
        for (int i = 1; i <= 2; i++)
        {
            listOfValues.Add((string)obj["properties"]?[$"item{i}"]["dataType"]);
        } 
    

    !更多关于linq to json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多