17841

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

The intance type is not clear. I am using <strong>Foo</strong> 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,

<strong>json result</strong>

{"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 ?

<strong>EDIT</strong>:

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

Answer1:

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

Answer2:

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

<ol> <li>deserialize</li> <li>do your stirng manipulation</li> <li>re-serialize</li> </ol>

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

Recommend

  • Having trouble with async and ListAdapter can you help out?
  • Bind JSON key value pairs to table template in polymer dart
  • Alamofire and Reachability.swift not working on xCode8-beta5
  • Implementing “partial void” in VB
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • What's the purpose of QString?
  • gspread or such: help me get cell coordinates (not value)
  • How do I exclude a dependency in provided scope when running in Maven test scope?
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • Play WS (2.2.1): post/put large request
  • Q promise. Difference between .when and .then
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Different response to non-authenticated users and AJAX calls
  • Fetching methods from BroadcastReceiver to update UI
  • Updating server-side rendering client-side
  • Symfony2: How to get request parameter
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • GridView Sorting works once only
  • How to pass list parameters for each object using Spring MVC?
  • AT Commands to Send SMS not working in Windows 8.1
  • php design question - will a Helper help here?
  • AngularJs get employee from factory
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • WPF Applying a trigger on binding failure
  • C# - Getting references of reference
  • Angular 2 constructor injection vs direct access
  • How do I configure my settings file to work with unit tests?
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Is it possible to post an object from jquery to bottle.py?
  • sending mail using smtp is too slow
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • Busy indicator not showing up in wpf window [duplicate]
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?