none
How to parse a object using System.Json RRS feed

  • Question

  • I have the following code which works fine:

    using Newtonsoft.Json.Linq;

    JObject o = JObject.Parse(content);
                string b = (string)o["PowerState"];
                Console.WriteLine(b);
                Console.ReadLine();

    However I don't want to use namespace Newtonsoft.Json.Linq; instead I want to use System.Json. When I include System.Json it goes undefined. I checked System.Json page and Googled around.  They suggest to use the following many namespace. Nothing seems to work. Could you please give me an example for a JSON Parser using Syste.Json. I do have .NET 4.6.2 and using C# with VS 2017. Thanks

    using System.Web.Script;

    using System.Web.Script.Serialization;

    using System.Runtime.Serialization;




    Thursday, September 28, 2017 7:11 PM

Answers

  • Hello ananda,

    I'm so sorry for the  delay reply , Because of some reason I can not answer you timely.

    If you just want to use  MSFT libraries , .NET comes with two kinds of JSON serialization itself ,They are System.Runtime.Serialization.dll and System.Web.Extensions.dll.

    >> I would like to do the same job not using NewtonSoft but using MSFT libraries and MSFT defined namespace

    I suggest you could add reference  (System.Web.Extensions) and the following is a simple example.

    string json = @"{
                    'Email': 'james@example.com',
                    'Active': true,
                    'CreatedDate': '2013-01-20T00:00:00Z',
                    'Roles': [
                    {'User':'111','Admin':'123'}
                    ]}";
    
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                dynamic dobj = jsonSerializer.Deserialize<dynamic>(json);
                string result = dobj["Email"].ToString();
                object result1 = dobj["Roles"][0]["User"];

    If you have any issues, please feel free to contact me.

    Sioncerely,

    neil hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, October 4, 2017 12:32 PM
    Moderator

All replies

  • Is there a compelling reason for not using Newton's library? It's pretty much the de facto standard for working with json.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, September 28, 2017 10:40 PM
    Moderator
  • Yes very compelling reasons, that is the main idea of my work too. All the software modules I use has to be Microsoft made. A simple Hello world kind of program would be greatly appreciated. It need not use System.Json. It can use any other namespace as long is it MSFT supported.  In other words my basic need is 

    1. Given an object I want a JSON parser to parse it. 

    2. The software used to do this Parser has to be MSFT product. 

    Thanks 

    Ananda

    Friday, September 29, 2017 12:03 AM
  • Hello ananda,

    Sysytem.json is only used on the SilverLight  platform, it  is a deprecated application framework for writing and running rich Internet applications. You can't use it without SilverLight environment.

    >>It can use any other namespace as long is it MSFT supported.  In other words my basic need is

    The System.Runtime.Serialization.dll is a good choice to meet your requirement. The following is a good example for you reference.

    static void Main(string[] args)
            {
                Simple simple = new Simple
                {
                    Id = 2,
                    value = "test"
                };
    
                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Simple));
                MemoryStream ms = new MemoryStream();
                js.WriteObject(ms, simple);
    
                ms.Position = 0;
                StreamReader sr = new StreamReader(ms);
                string s1 = sr.ReadToEnd();
                Console.WriteLine(s1);
                sr.Close();
                ms.Close();
    
    
               // Deserialization takes JSON - formatted data and converts it into a .NET object in memory
    
                DataContractJsonSerializer js1 = new DataContractJsonSerializer(typeof(Simple));
                MemoryStream ms1 = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(s1));
                Simple fireBall = (Simple)js1.ReadObject(ms1);
    
            }
        }
    
        public class Simple {
    
            public int Id { get; set; }
            public string value { get; set; }
        }

    Sincerely,

    neil hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, September 29, 2017 6:35 AM
    Moderator
  • System.Json for .NET Core is not deprecated. It is available in NuGet and has been updated as recently as 2 months ago.

    I agree with the OP that using Newtson.Json throughout code is a bad idea. I'm surprised no one has created a simple interface to wrap JSON serialization like we have done for everything else. There are many issues with Newtson's implementation including a rather huge breaking change a while back that they pushed out in a minor update that broke most existing serialization code. When people reported it the Newtson devs called it a "bug" in design and, rather than remotely considering backwards compatibility, fixed it without warning anyone. The official response was "your code is broken, fix it". At this point I lost all faith in the owners of this library and started actively looking for other implementations. There are many other implementations available and most are a lot faster than Newtson's. I just wish the ASP.NET team would switch to a generic interface implementation so I can eliminate this library from our dependencies entirely.

    As for the original question, the closest thing available in .NET proper is DataContractJsonSerializer which can do JSON serialization. If you aren't tied to the framework implementation then use one of the many other JSON implementations. 

    Michael Taylor
    http://www.michaeltaylorp3.net

    Friday, September 29, 2017 1:59 PM
    Moderator
  • Thank you very much Hu. The json file we wish to parse is the response we get by sending a https request to a URI. We use the webclient() function to do this. This json response is however very large and we are looking to extract one particular key value pair from it. So does that mean that we have to now convert this json data into c# classes(by maybe json2csharp.com) and add all those classes to the code as well to deserialize it? I used the same methodology that you had suggested but when converting my json response to classes, we were getting multiple errors that were probably a result of how the json response is formatted. Then that would be too much of work and NewtonSoft is doing it for us. Does a MSFT supported dll has this capability. My guess is NewtonSoft is traversing all base classes and filling in the derived classes and then making a meaningful dump. 

    My code is simply 5 lines and it works like a charm and the data is huge with nested classes. I would like to do the same job not using NewtonSoft but using MSFT libraries and MSFT defined namespace

    using System;

    using Newtonsoft.Json.Linq;

    var uri = "https://xxx.yyy.z.abcd/myfolder/myfile ....."

    var syncClient = new WebClient();

    var content = syncClient.DownloadString(uri); 

    JObject o = JObject.Parse(content);

    string b = (string)o["MySearchString"];

    Please clarify. thanks


    Friday, September 29, 2017 5:16 PM
  • I have been Googling and I dont see anyway out other than using NewtonSoft.dll so I have convinced myself and others that we have to make an exception for now and move on using NewtonSoft. So Hu and others please consider this case as closed. If I find a viable solution in the future I will post.

    Thanks

    ananda

     
    Tuesday, October 3, 2017 4:16 PM
  • Hi ananda vardhana,

    This looks like a homework to me.


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Tuesday, October 3, 2017 8:41 PM
    Moderator
  • Hello ananda,

    I'm so sorry for the  delay reply , Because of some reason I can not answer you timely.

    If you just want to use  MSFT libraries , .NET comes with two kinds of JSON serialization itself ,They are System.Runtime.Serialization.dll and System.Web.Extensions.dll.

    >> I would like to do the same job not using NewtonSoft but using MSFT libraries and MSFT defined namespace

    I suggest you could add reference  (System.Web.Extensions) and the following is a simple example.

    string json = @"{
                    'Email': 'james@example.com',
                    'Active': true,
                    'CreatedDate': '2013-01-20T00:00:00Z',
                    'Roles': [
                    {'User':'111','Admin':'123'}
                    ]}";
    
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                dynamic dobj = jsonSerializer.Deserialize<dynamic>(json);
                string result = dobj["Email"].ToString();
                object result1 = dobj["Roles"][0]["User"];

    If you have any issues, please feel free to contact me.

    Sioncerely,

    neil hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, October 4, 2017 12:32 PM
    Moderator
  • You need to annotate Simple and its two members with the         [DataContract] <g class="gr_ gr_60 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="60" id="60">attibute</g>, e.g.

            [DataContract]
            sealed class foo
            {
                [DataMember(Name = "bar")]
                public string bar { get; set; }
            }

     
    Monday, April 8, 2019 9:53 PM