How to Serialize Object to JSON

How do I turn a C# object into a JSON string in .NET?

Please Note

Microsoft recommends that you DO NOT USE JavaScriptSerializer

See the header of the documentation page:

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.



Original answer:

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
public int year;
public int month;
public int day;
}

public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}

class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}

How to serialize Object to JSON?

Easy way to do it without annotations is to use Gson library

Simple as that:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

How to make a class JSON serializable

Do you have an idea about the expected output? For example, will this do?

>>> f  = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'

In that case you can merely call json.dumps(f.__dict__).

If you want more customized output then you will have to subclass JSONEncoder and implement your own custom serialization.

For a trivial example, see below.

>>> from json import JSONEncoder
>>> class MyEncoder(JSONEncoder):
def default(self, o):
return o.__dict__

>>> MyEncoder().encode(f)
'{"fname": "/foo/bar"}'

Then you pass this class into the json.dumps() method as cls kwarg:

json.dumps(cls=MyEncoder)

If you also want to decode then you'll have to supply a custom object_hook to the JSONDecoder class. For example:

>>> def from_json(json_object):
if 'fname' in json_object:
return FileItem(json_object['fname'])
>>> f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}')
>>> f
<__main__.FileItem object at 0x9337fac>
>>>

How to serialize object to json with type info using Newtonsoft.Json?

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
var converters = serializer.Converters.Where(x => !(x is TypeInfoConverter)).ToArray();

var jObject = JObject.FromObject(value);
jObject.AddFirst(new JProperty("Type", value.GetType().Name));
jObject.WriteTo(writer, converters);
}

How to serialize or convert Swift objects to JSON?

In Swift 4, you can inherit from the Codable type.

struct Dog: Codable {
var name: String
var owner: String
}

// Encode
let dog = Dog(name: "Rex", owner: "Etgar")

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(dog)
let json = String(data: jsonData, encoding: String.Encoding.utf16)

// Decode
let jsonDecoder = JSONDecoder()
let secondDog = try jsonDecoder.decode(Dog.self, from: jsonData)

Serializing an object to JSON in which the type is not known

You can make your method generic:

public string Serialize<T>(T obj)
{
JsonSerializerOptions o = new JsonSerializerOptions();
o.WriteIndented = true;

return JsonSerializer.Serialize<T>((obj, o));
}

How to serialize an object to a JSON string property instead of an object using Json.Net

Use a custom JsonConverter and you can control your conversion to output whatever you want.

Something like:

    public class BarConverter : JsonConverter
{

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

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var bar = value as Bar;
serializer.Serialize(writer, bar.Name);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Note: if you need to read to, you'll need to implement that here too
// otherwise just throw a NotImplementException and override `CanRead` to return false
throw new NotImplementedException();
}
}

Then you can either decorate your property or the Bar class (depending on whether you always want Bar serialized like this, or only for this property) with the JsonConverterAttribute:

[JsonConverter(typeof(BarConverter))]
public Bar Bar { get; set; }

Or:

[JsonConverter(typeof(BarConverter))]
public class Bar

Another "quick and dirty" way to do it is to just have a shadow property that will be serialized:

public class Foo
{
[JsonProperty("bar")] // this will be serialized as "bar"
public string BarName
{
get { return Bar.Name; }
}

[JsonIgnore] // this won't be serialized
public Bar Bar { get; set; }
}

Note if you want to be able to read then you'd need to provide a setter too and figure out how to convert the string name back to an instance of Bar. That's where the quick and dirty solution gets a little unpleasant because you don't have a easy way to restrict setting BarName to just during deserialization.



Related Topics



Leave a reply



Submit