我遇到了以下情况,有人可以帮我实现以下目标吗?
例如,如果我有这个类: -
public class Sample
{
public String name {get;set;}
public MyClass myclass {get;set;}
}
我的Myclass
将如下:
public class MyClass
{
public String p1 {get;set;}
public String p2 {get;set;}
}
当我使用Json.net
序列化Sample类的对象时,我得到如下所示,它运行良好。
{
"name":"...",
"myclass":
{
"p1":"...",
"p2":"..."
}
}
它是正确的,但我想知道是否有可能获得如下的json字符串?
{
"name":"...",
"p1":"...",
"p2":"..."
}
答案 0 :(得分:22)
您可以创建匿名对象并对其进行序列化:
var sample = new Sample {
name = "Bob",
myclass = new MyClass {
p1 = "x",
p2 = "y"
}};
string json = JsonConvert.SerializeObject(new {
sample.name,
sample.myclass.p1,
sample.myclass.p2
});
结果
{"name":"Bob","p1":"x","p2":"y"}
但我建议您使用Sample
类的默认序列化,或者创建将序列化为您的格式的类(即将MyClass
属性移动到Sample
)。
UPDATE :您可以使用自定义转换器,它会将对象展平并将所有内部对象属性序列化为顶级对象属性:
public class FlattenJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
return;
}
JObject o = (JObject)t;
writer.WriteStartObject();
WriteJson(writer, o);
writer.WriteEndObject();
}
private void WriteJson(JsonWriter writer, JObject value)
{
foreach (var p in value.Properties())
{
if (p.Value is JObject)
WriteJson(writer, (JObject)p.Value);
else
p.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return true; // works for any type
}
}
用法:
string json = JsonConvert.SerializeObject(sample, new FlattenJsonConverter());
或者您可以简单地将匿名类型创建隐藏到自定义转换器中,如果您只需要一种类型的此行为:
public class SampleJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
Sample sample = (Sample)value;
JToken t = JToken.FromObject(new {
sample.name,
sample.myclass.p1,
sample.myclass.p2
});
t.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Sample);
}
}