gpt4 book ai didi

c# - 如何在转换为 json 时格式化对象中仅为字符串的属性?

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:33 26 4
gpt4 key购买 nike

实例类型不明确。我以 Foo 为例。我有一个格式化方法和一个类,如下所示,

public string FormatMethod(string s){
//for example pattern ++
return "++" + s + "++";
}

public class Foo{
public int FooId {get;set;}
public string Name {get;set;}
public string Desciption {get;set;}
}

var foo = new Foo{ FooId = 1, Name = "FooName", Description = "Bla bla bla" };
// or
var list = new List<Foo>();
list.Add(foo);

var json = JsonConvert.SerializeObject(list);
//or
var jsonlist = JsonConvert.SerializeObject(foo);

我希望将对象或列表中的字符串属性在转换为 json 时发送到格式化方法,

我希望 json 结果如下所示,

json 结果

 {"FooId": 1 , "Name": "++FooName++", "Description" : "++Bla bla bla++" }

或作为列表

[{"FooId": 1 , "Name": "++FooName++", "Description" : "++Bla bla bla++" }]

我该怎么做?

编辑:

我想在对象被序列化时应用任何模式,例如名称为'FooName',序列化后需要为'++FooName++'。

我认为可以使用 myconverter 来完成,但是怎么做呢?

例如:

public class MyConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// need to do something in here, I don't know what to do.
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
}

最佳答案

转换器:

class StringFormatConverter : JsonConverter
{
public string Format { get; set; }

public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(string.Format(Format, value));
}

public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotSupportedException();
}

public override bool CanConvert (Type objectType)
{
return objectType == typeof(string);
}
}

用法:

Console.WriteLine(JsonConvert.SerializeObject(new List<Foo> {
new Foo { FooId = 1, Name = "FooName", Description = "Bla bla bla" }
}, new JsonSerializerSettings {
Converters = { new StringFormatConverter { Format = "++{0}++" } }
}));

输出:

[{"FooId":1,"Name":"++FooName++","Description":"++Bla bla bla++"}]

如果需要限制对特定属性的字符串修改,可以使用JsonConverterAttributeJsonPropertyAttribute.ItemConverterType (并从 JsonSerializerSettings 中删除“全局”转换器)。

关于c# - 如何在转换为 json 时格式化对象中仅为字符串的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15810087/

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