How to parse JSON without JSON.NET library?
Asked Answered
N

8

85

I'm trying to build a Metro application for Windows 8 on Visual Studio 2011. and while I'm trying to do that, I'm having some issues on how to parse JSON without JSON.NET library (It doesn't support the metro applications yet).

Anyway, I want to parse this:

{
   "name":"Prince Charming",
   "artist":"Metallica",
   "genre":"Rock and Metal",
   "album":"Reload",
   "album_image":"http:\/\/up203.siz.co.il\/up2\/u2zzzw4mjayz.png",
   "link":"http:\/\/f2h.co.il\/7779182246886"
}
Novitiate answered 5/3, 2012 at 19:59 Comment(5)
You can do it with string manipulation like those of us did before JSON.NET and other libraries came about.Irrelevant
Use JavascriptSerializer. Take a look at this answer: #8405958Far
You shouldn't be asking this, MS has not shown more love for anything like it has to Json. There's Json in System.Web.Helpers, there's JsonQueryStringConverter in System.ServiceModel.Web, there's JavascriptSerializer in System.Web.Script.Serialization, DataContractJsonSerializer in System.Runtime.Serialization.Json... Not at all confusing.Infrequency
Heck MS has even decided to include third party Json.NET in its ASP.NET Web API. If you thought that wasn't enough, MS is coming up with System.Json but currently is unfit for consumption. And Windows 8 is a special case for MS, so there is also JsonValue in Windows.Data.Json which is only for Windows 8 and above.Infrequency
As of late 2016: It seems that Microsoft has embraced Json.NET and possibly abandoned the never-officially-released System.Json: msdn.microsoft.com/en-us/library/… talks about "preview" and the Nuget package is both (still) labeled "Beta" and has been unlisted, suggesting deprecation. (There is a released System.Json, but it is Silverlight-only).Devereux
A
102

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;


JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

Arrangement answered 5/3, 2012 at 20:3 Comment(10)
I dont have System.Json namespace... I'm using visual studio 2011 ultimate and when im trying to add reference it gives me an empty list...Novitiate
You need to add a reference to the System.Runtime.Serialization assembly.Arrangement
It seems to be in the Windows.Data.Json; now as I can see in my Metro App.Luster
Use Nuget to install system.json : Install-Package System.JsonGuido
Is there an example of this strongly-typed with generics? Would like to not waste the time writing something that I don't have to. :)Heavyhearted
If the package cannot be found, make sure you add the version number. Example: PM> Install-Package System.Json -Version 4.0.20126.16343. Find the current version here: nuget.org/packages/System.JsonZaibatsu
System.Json is still in beta and so Nuget package seems to be the way to get it. It is not built-in the most recent full Framework V 4.5.1. Personally I like Json.Net's API which is much less verbose and faster than Windows.Data.Json or System.Json. See james.newtonking.com/json/help/html/…Cataract
cant find system.jsonCavicorn
@krowe2 - Last time I checked Json.NET was MIT licenced: github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.mdCataract
The type or namespace name 'JsonValue' could not be found (are you missing a using directive or an assembly reference?) I'm targeting .NET Framework 4.7.2 and I have added a reference to the System.Runtime.Serialization assembly. I want to avoid using any NuGet packages, otherwise I might as well just use NewtonSoft.Nominate
S
40

I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)

public static class JSONSerializer<TType> where TType : class
{
    /// <summary>
    /// Serializes an object to JSON
    /// </summary>
    public static string Serialize(TType instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(TType));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, instance);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// DeSerializes an object from JSON
    /// </summary>
    public static TType DeSerialize(string json)
    {
        using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(typeof(TType));
            return serializer.ReadObject(stream) as TType;
        }
    }
}

So, if you had a class like this...

[DataContract]
public class MusicInfo
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Artist { get; set; }

    [DataMember]
    public string Genre { get; set; }

    [DataMember]
    public string Album { get; set; }

    [DataMember]
    public string AlbumImage { get; set; }

    [DataMember]
    public string Link { get; set; }

}

Then you would use it like this...

var musicInfo = new MusicInfo
{
     Name = "Prince Charming",
     Artist = "Metallica",
     Genre = "Rock and Metal",
     Album = "Reload",
     AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
     Link = "http://f2h.co.il/7779182246886"
};

// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);

// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);
Stuartstub answered 5/3, 2012 at 20:4 Comment(6)
how do I use it? it keeps asking me for TType, whats that?Novitiate
If your type (class) was called MyType, you would use it like this: JSONSerializer<MyType>.Serialize() and JSONSerializer<MyType>.Deserialize(myInstanceOfMyType)Stuartstub
Looks like dtb has a newer native way (answered above) if you're using v4.5 of the Framework.Stuartstub
You have to use Encoding.UTF8.GetString(stream.ToArray()); if you want to support unicode.Igbo
How do you deal, if you have an object inside your custom object that does not have a DataContract and DataMember attribute?Vardhamana
@Stuartstub How to deal same problem for list of objects i.e. if we want to write 100s of objects to a file and then restore same file's contents into a list of same objects?Leucoma
A
11

For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.

Example usage:

Given the json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

You could parse it into a RadComboBoxClientState object like this:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

Link to docs

Auberbach answered 27/2, 2015 at 21:6 Comment(0)
A
7

I needed a JSON serializer and deserializer without any 3rd party dependency or nuget, that can support old systems, so you don't have to choose between Newtonsoft.Json, System.Text.Json, DataContractSerializer, JavaScriptSerializer, etc. depending on the target platform.

So I have started this "ZeroDepJson" open source (MIT licensed) project here:

https://github.com/smourier/ZeroDepJson

It's just one C# file ZeroDepJson.cs, compatible with .NET Framework 4.x to .NET Core/5/6/7+.

Note absolute performance is not a goal. Although its performance is, I hope, decent, if you're after the best performing JSON serializer / deserializer ever, then don't use this.

Agenda answered 6/5, 2021 at 11:40 Comment(1)
I love libraries like this. Probably will use this one for a SQL SSIS package script that needs to parse JSON from a REST response. Thanks!!!Evergreen
A
6

Have you tried using JavaScriptSerializer ? There's also DataContractJsonSerializer

Alchemize answered 5/3, 2012 at 20:2 Comment(3)
Nope, can you explain to me whats that? thanx dudeNovitiate
DataContract: msdn.microsoft.com/en-us/library/bb908432.aspx JavaScriptSerializer: msdn.microsoft.com/en-us/library/…Alchemize
Re JavaScriptSerializer: As of this writing, its MSDN page recommends using Json.NET instead.Devereux
A
3

I have written a small construct to do that long back, it requires System.Runtime.Serialization.Json namespace. It uses DataContractJsonSerializer to serialize & deserialize object with a static method JConvert.

It works with small set of data but haven't tested with big data source.

JsonHelper.cs

// Json Serializer without NewtonSoft
public static class JsonHelper
{
    public static R JConvert<P,R>(this P t)
    {       
        if(typeof(P) == typeof(string))
        {
            var return1 =  (R)(JsonDeserializer<R>(t as string));
            return return1;
        }
        else
        {
            var return2 =  (JsonSerializer<P>(t));
            R result = (R)Convert.ChangeType(return2, typeof(R));
            return result;
        }   
    }
    
    private static String JsonSerializer<T>(T t)
    {
        var stream1 = new MemoryStream();
        var ser = new DataContractJsonSerializer(typeof(T));
        ser.WriteObject(stream1, t);
        stream1.Position = 0;
        var sr = new StreamReader(stream1);     
        return (sr.ReadToEnd());
    }
    
    private static T JsonDeserializer<T>(string jsonString)
    {
        T deserializedUser = default(T);
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        var ser = new DataContractJsonSerializer(typeof(T));
        deserializedUser = (T)ser.ReadObject(ms);// as T;
        ms.Close();
        return deserializedUser;
    }
}

Syntax:

To use the JsonHelper you need to call

JConvert<string,object>(str); //to Parse string to non anonymous <object>
JConvert<object,string>(obj); //to convert <obj> to string

Example:

Suppose we have a class person

public class person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
}

var obj = new person();//"vinod","srivastav");
obj.FirstName = "vinod";
obj.LastName = "srivastav";

To convert the person object we can call:

var asText = JsonHelper.JConvert<person,string>(obj); //to convert <obj> to string

var asObject = JsonHelper.JConvert<string,person>(asText); //to convert string to non-anonymous object
  

EDIT:2023

Since the construct & was a bit difficult to use & understand, here is another simple implementation to imitate Javascript JSON object withJSON.stringify() & JSON.parse(). It also have an extension function ToJson() to work with anonymous objects which uses System.Web.Script.Serialization from system.Web.Extensions.dll to serialize object tot json.

using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;

public static class JSON
{

    public static string ToJson(this object dataObject)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(dataObject);        
    }
    
    public static T ToObject<T>(this string serializedData)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var deserializedResult = js.Deserialize<T>(serializedData);
        return deserializedResult;
    }
    
    public static String Stringify<T>(T t)
    {
        var inmemory = new MemoryStream();
        var ser = new DataContractJsonSerializer(typeof(T));
        ser.WriteObject(inmemory, t);
        return (Encoding.UTF8.GetString(inmemory.ToArray()));
    }
    
    public static T Parse<T>(string jsonString)
    {
        T deserializedUser = default(T);
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        var ser = new DataContractJsonSerializer(typeof(T));
        deserializedUser = (T)ser.ReadObject(ms);// as T;
        ms.Close();
        return deserializedUser;
    }
}

Now to use this one you simply have to write:

//to convert <obj> to string
var asText = JSON.Stringify(obj); 

//to convert string to non-anonymous object
var asObject = JSON.Parse<person>(asText); 

//for anonymous object
var ao = new {Name="Vinod", Surname = "Srivastav" };
var asText = ao.ToJson();


In .NET 6.0

With .NET 6.0 you just need to add

using System.Text.Json;
using System.Text.Json.Serialization;

Json.cs

public static class JSON
{
    public static string Stringify<T>(T t)
    {
        string jsonString = JsonSerializer.Serialize(t);
        return jsonString;
    }

    public static T Parse<T>(string jsonString)
    {
        T deserializedObject = JsonSerializer.Deserialize<T>(jsonString)!;
        return deserializedObject;
    }
}

And it still runs the above example: enter image description here

Aquilar answered 22/12, 2021 at 19:36 Comment(4)
how to use ? example ?Maryleemarylin
@GrayProgrammerz I have updated the answer with an example, see if it works for youAquilar
Thanks. between can I use it dynamically ? without person ? like Utf8Json ?Maryleemarylin
@GrayProgrammerz I have again updated the answer to include ToJson() this extension will work with anonymous object see example.Aquilar
S
1

You can use DataContractJsonSerializer. See this link for more details.

Saga answered 5/3, 2012 at 20:4 Comment(3)
I tried that with this code { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Song)); Song item = (Song)ser.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(song))); Debug.WriteLine(item.name); } and it gives me an errorNovitiate
The error is Type 'Test1.Song' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.Novitiate
@EliRevah - You need to define the data contract for the deserialization with the [DataContract] attribute for the class and add [DataMember] attribute for each member.Saga
P
1
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace OTL
{
    /// <summary>
    /// Before usage: Define your class, sample:
    /// [DataContract]
    ///public class MusicInfo
    ///{
    ///   [DataMember(Name="music_name")]
    ///   public string Name { get; set; }
    ///   [DataMember]
    ///   public string Artist{get; set;}
    ///}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class OTLJSON<T> where T : class
    {
        /// <summary>
        /// Serializes an object to JSON
        /// Usage: string serialized = OTLJSON&lt;MusicInfo&gt;.Serialize(musicInfo);
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string Serialize(T instance)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, instance);
                return Encoding.Default.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// DeSerializes an object from JSON
        /// Usage:  MusicInfo deserialized = OTLJSON&lt;MusicInfo&gt;.Deserialize(json);
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json))
                throw new Exception("Json can't empty");
            else
                try
                {
                    using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
                    {

                        var serializer = new DataContractJsonSerializer(typeof(T));
                        return serializer.ReadObject(stream) as T;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Json can't convert to Object because it isn't correct format.");
                }
        }
    }
}
Probe answered 22/10, 2020 at 2:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.