Convert JSON String To C# Object

2019-01-01 01:23发布

问题:

Trying to convert a JSON string into an object in C#. Using a really simple test case:

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject(\"{ \\\"test\\\":\\\"some data\\\" }\");

The problem is that routes_list never gets set; it\'s an undefined object. Any ideas?

回答1:

It looks like you\'re trying to deserialize to a raw object. You could create a Class that represents the object that you\'re converting to. This would be most useful in cases where you\'re dealing with larger objects or JSON Strings.

For instance:

  class Test {

      String test; 

      String getTest() { return test; }
      void setTest(String test) { this.test = test; }

  }

Then your deserialization code would be:

   JavaScriptSerializer json_serializer = new JavaScriptSerializer();
   Test routes_list = 
          (Test)json_serializer.DeserializeObject(\"{ \\\"test\\\":\\\"some data\\\" }\");

More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx



回答2:

Or, you can use the Newtownsoft.Json library as follows:

using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);

Where T is your object type that matches your JSON string.



回答3:

You probably don\'t want to just declare routes_list as an object type. It doesn\'t have a .test property, so you really aren\'t going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.

If you really want this code to work as you have it, you\'ll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here\'s the code to do it that way:

var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject(\"{ \\\"test\\\":\\\"some data\\\" }\");
Console.WriteLine(routes_list[\"test\"]);

If you want to use the dynamic keyword, you can read how here.

If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:

class MyProgram {
    struct MyObj {
        public string test { get; set; }
    }

    static void Main(string[] args) {
        var json_serializer = new JavaScriptSerializer();
        MyObj routes_list = json_serializer.Deserialize<MyObj>(\"{ \\\"test\\\":\\\"some data\\\" }\");
        Console.WriteLine(routes_list.test);

        Console.WriteLine(\"Done...\");
        Console.ReadKey(true);
    }
}


回答4:

Using dynamic object with JavaScriptSerializer.

JavaScriptSerializer serializer = new JavaScriptSerializer(); 
dynamic item = serializer.Deserialize<object>(\"{ \\\"test\\\":\\\"some data\\\" }\");
string test= item[\"test\"];

//test Result = \"some data\"


回答5:

Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

one line code solution.

var myclass = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Jsonstring);

Myclass oMyclass = Newtonsoft.Json.JsonConvert.DeserializeObject<Myclass>(Jsonstring);


回答6:

Here\'s a simple class I cobbled together from various posts.... It\'s been tested for about 15 minutes, but seems to work for my purposes. It uses JavascriptSerializer to do the work, which can be referenced in your app using the info detailed in this post.

The below code can be run in LinqPad to test it out by:

  • Right clicking on your script tab in LinqPad, and choosing \"Query Properties\"
  • Referencing the \"System.Web.Extensions.dll\" in \"Additional References\"
  • Adding an \"Additional Namespace Imports\" of \"System.Web.Script.Serialization\".

Hope it helps!

void Main()
{
  string json = @\"
  {
    \'glossary\': 
    {
      \'title\': \'example glossary\',
        \'GlossDiv\': 
        {
          \'title\': \'S\',
          \'GlossList\': 
          {
            \'GlossEntry\': 
            {
              \'ID\': \'SGML\',
              \'ItemNumber\': 2,          
              \'SortAs\': \'SGML\',
              \'GlossTerm\': \'Standard Generalized Markup Language\',
              \'Acronym\': \'SGML\',
              \'Abbrev\': \'ISO 8879:1986\',
              \'GlossDef\': 
              {
                \'para\': \'A meta-markup language, used to create markup languages such as DocBook.\',
                \'GlossSeeAlso\': [\'GML\', \'XML\']
              },
              \'GlossSee\': \'markup\'
            }
          }
        }
    }
  }

  \";

  var d = new JsonDeserializer(json);
  d.GetString(\"glossary.title\").Dump();
  d.GetString(\"glossary.GlossDiv.title\").Dump();  
  d.GetString(\"glossary.GlossDiv.GlossList.GlossEntry.ID\").Dump();  
  d.GetInt(\"glossary.GlossDiv.GlossList.GlossEntry.ItemNumber\").Dump();    
  d.GetObject(\"glossary.GlossDiv.GlossList.GlossEntry.GlossDef\").Dump();   
  d.GetObject(\"glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso\").Dump(); 
  d.GetObject(\"Some Path That Doesnt Exist.Or.Another\").Dump();   
}


// Define other methods and classes here

public class JsonDeserializer
{
  private IDictionary<string, object> jsonData { get; set; }

  public JsonDeserializer(string json)
  {
    var json_serializer = new JavaScriptSerializer();

    jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
  }

  public string GetString(string path)
  {
    return (string) GetObject(path);
  }

  public int? GetInt(string path)
  {
    int? result = null;

    object o = GetObject(path);
    if (o == null)
    {
      return result;
    }

    if (o is string)
    {
      result = Int32.Parse((string)o);
    }
    else
    {
      result = (Int32) o;
    }

    return result;
  }

  public object GetObject(string path)
  {
    object result = null;

    var curr = jsonData;
    var paths = path.Split(\'.\');
    var pathCount = paths.Count();

    try
    {
      for (int i = 0; i < pathCount; i++)
      {
        var key = paths[i];
        if (i == (pathCount - 1))
        {
          result = curr[key];
        }
        else
        {
          curr = (IDictionary<string, object>)curr[key];
        }
      }
    }
    catch
    {
      // Probably means an invalid path (ie object doesn\'t exist)
    }

    return result;
  }
}


回答7:

You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.

Class for the type of object you receive:

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }

}

Code:

static void Main(string[] args)
{

      string json = \"{\\\"ID\\\": 1, \\\"Name\\\": \\\"Abdullah\\\"}\";

      User user = JsonConvert.DeserializeObject<User>(json);

      Console.ReadKey();
}

this is a very simple way to parse your json.



回答8:

add this ddl to reference to your project: System.Web.Extensions.dll

use this namespace: using System.Web.Script.Serialization;

public class IdName
{
    public int Id { get; set; }
    public string Name { get; set; }
}


   string jsonStringSingle = \"{\'Id\': 1, \'Name\':\'Thulasi Ram.S\'}\".Replace(\"\'\", \"\\\"\");
   var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);

   string jsonStringCollection = \"[{\'Id\': 2, \'Name\':\'Thulasi Ram.S\'},{\'Id\': 2, \'Name\':\'Raja Ram.S\'},{\'Id\': 3, \'Name\':\'Ram.S\'}]\".Replace(\"\'\", \"\\\"\");
   var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);


回答9:

Another fast and easy way to semi-automate these steps is to:

  1. take the JSON you want to parse and paste it here: http://json2csharp.com/ then copy and paste the resulting into a new class (ex: MyClass) in visual studio.
  2. Rename \"RootObject\" in the output from json2csharp to \"MyClass\" or whatever you called it.
  3. In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.

Now use code like:

WebClient client = new WebClient();

string myJSON = client.DownloadString(\"https://URL_FOR_JSON.com/JSON_STUFF\");

var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);


回答10:

As tripletdad99 said

var result = JsonConvert.DeserializeObject<T>(json);

but if you don\'t want to create an extra object you can make it with Dictionary instead

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(json_serializer);


回答11:

Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here \"MenuInfo\" is my C# class object.

JsonTextReader reader = null;
try
{
    WebClient webClient = new WebClient();
    JObject result = JObject.Parse(webClient.DownloadString(\"YOUR URL\"));
    reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
    reader.SupportMultipleContent = true;
}
catch(Exception)
{}

JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);


回答12:

First you have to include library like:

using System.Runtime.Serialization.Json;

DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = \"{\\\"Description\\\":\\\"Share knowledge\\\",\\\"Name\\\":\\\"zahid\\\"}\";

using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
    BlogSite b = (BlogSite)desc.ReadObject(ms);
    Console.WriteLine(b.Name);
    Console.WriteLine(b.Description);
}


标签: c# json