Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET serialization if override ToString

I have a set of complex business objects that I'd like to serialize to Json for use in a web service. I'm currently using the DataContractJsonSerializer to product the Json, but it balks on deserialization because the default XmlReader can't handle Base64 strings.

After reading many positive reviews of Json.Net, I decided to give it a try. Surprisingly, the simplest case produces erroneous output if the business object overrides the ToString() method. Instead of generating JSON, it simply emits the string value.

For example, the following statement produces only a string, as the serializer appears to view the object as a simple string.

public class MyClass {
    public string Title{get;set;}
    public override ToString(){ return Title; }
    public string ToJson(){ 
        return JsonConvert.SerializeObject(this); 
    }
}

Instead of json formatted output, all I get is the title string. Do I have to mark the object in some special way to avoid this? Since the business object hierarchy includes many objects that override ToString(), I would rather avoid having to introduce special attributes, etc.

like image 753
John Holliday Avatar asked Sep 26 '13 18:09

John Holliday


People also ask

Can we override ToString () method in C#?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

How do I create a custom converter for JSON serialization?

Steps to follow the basic patternCreate a class that derives from JsonConverter<T> where T is the type to be serialized and deserialized. Override the Read method to deserialize the incoming JSON and convert it to type T . Use the Utf8JsonReader that's passed to the method to read the JSON.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is JSON serialization and deserialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


1 Answers

Is it possible that your actual class has a TypeConverterAttribute attached to it? I just ran into the exact same problem and found out that the TypeConverterAttribute was causing this. In thast case, this might help (at least it did for me).

This is very bad because you can inadvertently break your program (by simply adding a TypeConverter maybe for displaying the object in a PropertyGrid) without getting a compiler warning...

using Newtonsoft.Json;
using System;
using System.ComponentModel;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var with = new WithTypeConverter() { Bla = 12, Blub = "With" };
            var without = new WithoutTypeConverter() { Bla = 12, Blub = "Without" };

            Console.WriteLine(with);
            Console.WriteLine(JsonConvert.SerializeObject(with));

            Console.WriteLine(without);
            Console.WriteLine(JsonConvert.SerializeObject(without));
            Console.ReadKey();
        }
    }

    public class baseClass
    {
        public int Bla { get; set; }
        public string Blub { get; set; }

        public override string ToString()
        {
            return String.Format("{0}: {1}", this.GetType().Name, Blub);
        }
    }

    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class WithTypeConverter : baseClass
    {
    }

    public class WithoutTypeConverter : baseClass
    {
    }
}
like image 128
wexman Avatar answered Oct 12 '22 23:10

wexman