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

Serializing a javascript class object?

You can use JSON.stringify, but be aware that it only serialize properties, not methods. So to unserialize an object, just create a dummy instance and use Object.assign to update the properties using the retrieved object:

function serialize(instance) {
var str = JSON.stringify(instance);
// save str or whatever
}

function unserialize(str, theClass) {
var instance = new theClass(); // NOTE: if your constructor checks for unpassed arguments, then just pass dummy ones to prevent throwing an error
var serializedObject = JSON.parse(str);
Object.assign(instance, serializedObject);
return instance;
}

Example:

function serialize(obj) {    var str = JSON.stringify(obj);    return str;}
function unserialize(str, theClass) { var instance = new theClass(); var serializedObject = JSON.parse(str); Object.assign(instance, serializedObject); return instance;}
// TEST CLASS
class TestClass { constructor(a, b) { this.a = a; this.b = b; }
sum() { return this.a + this.b; }}
// USAGE
var instance = new TestClass(5, 7);
var str = serialize(instance);
var retrievedInstance = unserialize(str, TestClass);
console.log(retrievedInstance.sum());

Serializing an ES6 class object as JSON

As with any other object you want to stringify in JS, you can use JSON.stringify:

JSON.stringify(yourObject);

class MyClass {  constructor() {    this.foo = 3  }}
var myClass = new MyClass()
console.log(JSON.stringify(myClass));

how to serialize a general object to Json and deserialize Json to the object in Java

Just Convert the QueryBuilder.update into string using toString() method

If you want to store,retrieve and execute the QueryBuilder.update query, you don't have to serialized and deserialized it into json.

String query = QueryBuilder.update("exp").with(QueryBuilder.set("data", "This is a test data")).toString();
//Now you can store the text query directly to cassandra
//And retrieve the text query
session.execute(query); //Execute the query

Here is the code of toString()

@Override
public String toString() {
try {
if (forceNoValues)
return getQueryString();
// 1) try first with all values inlined (will not work if some values require custom codecs,
// or if the required codecs are registered in a different CodecRegistry instance than the default one)
return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString();
} catch (RuntimeException e1) {
// 2) try next with bind markers for all values to avoid usage of custom codecs
try {
return maybeAddSemicolon(buildQueryString(new ArrayList<Object>(), CodecRegistry.DEFAULT_INSTANCE)).toString();
} catch (RuntimeException e2) {
// Ugly but we have absolutely no context to get the registry from
return String.format("built query (could not generate with default codec registry: %s)", e2.getMessage());
}
}
}

You can see that It's returning the actual query string

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


Related Topics



Leave a reply



Submit