Alan Alan - 3 months ago 9
ASP.NET (C#) Question

Serializing an object with NewtonSoft?

I am trying to serialize an object with Newtonsoft like this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;

string json = new Newtonsoft.Json.JsonConvert.SerializeObject(new
{
jlpt = "5"
});


as far as I can see the syntax seems okay but it gives me an error saying that SerializeObject does not exist. However when I click to check the reference I see it.

Can anyone point me to what I am doing wrong?

Answer

Remove new instance creation of Newtonsoft.Json.JsonConvert, because SerializeObject is a static method you don't need create a instance of the Newtonsoft.Json.JsonConvert to use it

string json = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                jlpt = "5"
            });

also if you add using Newtonsoft.Json; to the program then you simply use like this

string json = JsonConvert.SerializeObject(new
            {
                jlpt = "5"
            });