【问题标题】:Discard more extern object from json and take the inner [duplicate]从json中丢弃更多外部对象并获取内部[重复]
【发布时间】:2020-02-24 20:45:54
【问题描述】:

我有一个以包含所有其余部分的对象开头的 json:

{
 "mainObject": 
 {
    "other stuff here 1" : "aaa",
    "other stuff here 2" : "bbb",
    ...
    "other stuff here 2000" : "zassbbb"
 }
}

我得到整个 json 并将其放入对象中,我怎样才能丢弃“mainObject”部分而只获得最内部的部分?我会在我的对象中有:

    "other stuff here 1" : "aaa",
    "other stuff here 2" : "bbb",
    ...
    "other stuff here 2000" : "zassbbb"

【问题讨论】:

  • 请展示您到目前为止尝试过的内容。您使用的是Json.NET 还是System.Text.Json?基本上,您可以使用JObject 轻松完成
  • 我目前是作为字符串处理的 我从字符串的开头到结尾去掉了我不感兴趣的部分,但是代码很繁琐

标签: c# json asp.net-core json.net


【解决方案1】:

您需要将数据映射到代表 json 对象的类。 举个简单的例子,您可以将 json 粘贴到 http://json2csharp.com/。

然后您需要将 json 字符串反序列化为创建的类。

var obj = JsonConvert.DeserializeObject<YourClass>(yourJsonString);

然后访问 mainObject 中的数据:

var contents = obj.MainObject;
var example = contents.OtherStuffHere1;

内容变量现在将只包含主对象中的数据,示例变量将根据您的示例包含字符串“aaa”。

您可能需要添加 using 语句并安装 Newtonsoft nuget 包,具体取决于您的 dotnet 版本 使用 Newtonsoft.Json.Linq;

newtonsoft 网站上有很多示例和资源。

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

【讨论】:

    猜你喜欢
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    相关资源
    最近更新 更多