猿问

将嵌套的复杂 json 对象反序列化为一个字符串 c#

我有 JSON,它看起来像:


{

  "name": "foo",

  "settings": {

    "setting1": true,

    "setting2": 1

  }

}  

我知道如何使用 json2csharp.com 创建 C# 类来反序列化它。它们看起来像:


public class Settings

{

    public bool settings1 { get; set; }

    public int settings2 { get; set; }

}


public class RootObject

{

    public string name { get; set; }

    public Settings settings { get; set; }

}

但我想要的是简单地将其反序列化为


public class RootObject

{

    public string name { get; set; }

    public string settings { get; set; }

}

即,所有“设置”JSON 只需要保存为字符串——该 JSON 的结构不一致。那怎么办呢?谢谢!


DIEA
浏览 355回答 3
3回答

翻过高山走不出你

您可以在反序列化期间使用 aJToken来捕获您的未知数settings,然后使用第二个属性来允许您在需要时以字符串形式访问该 JSON。像这样设置你的类:public class RootObject{&nbsp; &nbsp; [JsonProperty("name")]&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; [JsonIgnore]&nbsp; &nbsp; public string Settings&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return SettingsToken != null ? SettingsToken.ToString(Formatting.None) : null; }&nbsp; &nbsp; &nbsp; &nbsp; set { SettingsToken = value != null ? JToken.Parse(value) : JValue.CreateNull(); }&nbsp; &nbsp; }&nbsp; &nbsp; [JsonProperty("settings")]&nbsp; &nbsp; private JToken SettingsToken { get; set; }}然后像往常一样反序列化:var root = JsonConvert.DeserializeObject<RootObject>(json);该Settings属性将包含settingsJSON的一部分作为字符串。如果您将对象重新序列化回 JSON,那么settings它将保留它之前的任何结构。您还可以将该Settings属性更改为其他一些 JSON 字符串,只要它格式正确。(如果不是,则将立即抛出异常。)这是一个往返演示:https : //dotnetfiddle.net/thiaWk

翻阅古今

尝试使用 Newtonsoft.Json 和 LINQ:string jsonText = @"{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'name': 'foo',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'settings': {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'settings1': true,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'settings2': 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }";JObject jObj = JObject.Parse(jsonText);var setting = jObj.Descendants()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .OfType<JProperty>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(p => p.Name == "settings")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .First()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Value.ToObject<Settings>();

偶然的你

尝试这个:public class RootObject&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public string name { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public Dictionary<string,object> settings { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; }小提琴:https : //dotnetfiddle.net/QN3nWL
随时随地看视频慕课网APP
我要回答