gpt4 book ai didi

c# - c#中将类的Inner属性序列化为Json对象

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:46 24 4
gpt4 key购买 nike

我有以下一组类(class)。

    public class ClassOne
{
[JsonProperty(PropertyName = "property1", NullValueHandling = NullValueHandling.Ignore)]
public string Prop1 { get; set; }

[JsonProperty(PropertyName = "property2", NullValueHandling = NullValueHandling.Ignore)]
public string Prop2 { get; set; }

public ClassTwo ClassTwo { get; set; }
}

public class ClassTwo
{
[JsonProperty(PropertyName = "property3", NullValueHandling = NullValueHandling.Ignore)]
public string Prop3 { get; set; }

[JsonProperty(PropertyName = "property4", NullValueHandling = NullValueHandling.Ignore)]
public string Prop4 { get; set; }
}

我需要你们的帮助来将 ClassOne 对象序列化为 json 对象。所需的输出是:我使用 Newtonsoft.Json for序列化。

{
"property1":"test",
"property2":"test",
"property3":"test",
"property4":"test",
}

最佳答案

谢谢大家!我使用自定义转换器对我的问题进行了如下排序。

    public class FlattenJsonConverter : JsonConverter
{
#region Public Methods

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var jToken = JToken.FromObject(value);
if (jToken.Type != JTokenType.Object)
{
jToken.WriteTo(writer);
return;
}

var jObject = (JObject)jToken;
writer.WriteStartObject();
WriteJson(writer, jObject);
writer.WriteEndObject();
}

private void WriteJson(JsonWriter writer, JObject value)
{
foreach (var property in value.Properties())
{
var jObject = property.Value as JObject;
if (jObject != null)
WriteJson(writer, jObject);
else
property.WriteTo(writer);
}
}

public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
return null;
}

public override bool CanConvert(Type objectType)
{
return true;
}

#endregion
}

用法:

    // To Flatten the Json result
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = new List<JsonConverter> { new FlattenJsonConverter() },
};

var serializedJsonObject = JObject.Parse(testclassObject, settings));

关于c# - c#中将类的Inner属性序列化为Json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com