尝试用c#将JSON字符串转换为对象。使用一个非常简单的测试用例:

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

问题是routes_list从未被设置;它是一个未定义的对象。什么好主意吗?


当前回答

使用动态对象JavaScriptSerializer。

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

//test Result = "some data"

其他回答

或者,你可以使用System.Text.Json库,如下所示:

using System.Text.Json;
...
var options = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });
var result = JsonSerializer.Deserialize<List<T>>(json, options);

T是匹配JSON字符串的对象类型。

System.Text.Json可以在: .NET Core 2.0及以上版本 .NET Framework 4.6.1及以上版本

使用Newtonsoft,您可以轻松完成您的要求。Json库。我正在写下下面的一个例子,看看它。

为您接收的对象类型初始化:

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

}

代码:

static void Main(string[] args)
{

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

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

      Console.ReadKey();
}

这是解析json的一种非常简单的方法。

这是一个简单的类,我从各种帖子....拼凑起来它已经测试了大约15分钟,但似乎符合我的目的。它使用JavascriptSerializer来做这项工作,这可以在你的应用程序中引用,使用这篇文章中详细的信息。

下面的代码可以运行在LinqPad测试它:

在LinqPad中右键单击脚本选项卡,并选择“查询” 属性” 在“附加引用”中引用“System.Web.Extensions.dll” 的“附加名称空间导入” “System.Web.Script.Serialization”。

希望能有所帮助!

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

另一种快速简单的半自动这些步骤的方法是:

take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down. Update the name in the top left to your class name, it defaults to "Welcome". In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft. app.quicktype.io generated serialize methods based on Newtonsoft. Alternatively, you can 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);

在c#中将JSON字符串转换为对象。使用下面的测试用例..这对我很管用。这里“MenuInfo”是我的c#类对象。

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