intance类型不清楚。我使用 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时将对象或列表中的字符串属性发送到format方法,
我希望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();
}
}
答案 0 :(得分:1)
转换器:
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++"}]
如果您需要将字符串修改限制为特定属性,则可以使用JsonConverterAttribute
和JsonPropertyAttribute.ItemConverterType
(并从JsonSerializerSettings
删除“全局”转换器。)
答案 1 :(得分:0)
执行此操作的正确方法可能是
喜欢这样
// build initial Json
var foo = new Foo { FooId = 1, Name = "FooName", Desciption = "Bla bla bla" };
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
string fooJson = json_serializer.Serialize(foo);
// change value in Json
Foo newFoo = json_serializer.Deserialize<Foo>(fooJson);
newFoo.Name = String.Format("++{0}++", newFoo.Name);
fooJson = json_serializer.Serialize(newFoo);
或者你可能在转换为json之前尝试格式化你的字符串
Foo foo = new Foo { FooId = 1, Name = "FooName", Desciption = "Bla bla bla" };
Foo formattedFoo = new Foo {
FooId = foo.FooId,
Name = String.Format("++{0}++", foo.Name),
Desciption = String.Format("++{0}++", foo.Desciption)
};
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
string fooJson = json_serializer.Serialize(formattedFoo);