Sinan AKYAZICI
Sinan AKYAZICI

Reputation: 3952

How to format properties that are only string in an object while converting to json?

The intance type is not clear. I am using Foo as example. I have a format method and a class like below,

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);

I would like the properties that are string in an object or in a list to send to the format method while converting to json,

I would like json result to be like below,

json result

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

or as a list

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

How can I do it ?

EDIT:

I would like to apply any pattern while the object being serilalized, for example The name that is 'FooName', it need to be '++FooName++' after serialize.

I think it can be done using myconverter, but how ?

for example:

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();
        }
    } 

Upvotes: 2

Views: 1168

Answers (2)

Athari
Athari

Reputation: 34295

Converter:

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);
    }
}

Usage:

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

Output:

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

If you need to limit string modification to specific properties, you can use JsonConverterAttribute and JsonPropertyAttribute.ItemConverterType (and remove "global" converter from JsonSerializerSettings).

Upvotes: 1

What's probably the proper way to do this is to

  1. deserialize
  2. do your stirng manipulation
  3. re-serialize

like so

// 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);

Or maybe you're trying to format your string before you convert to json like so

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);

Upvotes: 0

Related Questions