将 JSON 字符串转换为 JSON 对象 c#

本文关键字:JSON 对象 转换 字符串 | 更新日期: 2023-09-27 17:56:36

我在我的数据库中存储了这个字符串:

str = "{ "context_name": { "lower_bound": "value", "upper_bound": "value", "values": [ "value1", "valueN" ] } }"

这个字符串已经是JSON格式,但我想将其转换为JObject或JSON对象。

JObject json = new JObject();

我尝试了json = (JObject)str;演员表,但它不起作用,那我该怎么做?

将 JSON 字符串转换为 JSON 对象 c#

JObject为此定义了方法Parse

JObject json = JObject.Parse(str);

您可能需要参考 Json.NET 文档。

如果您不想要或不需要类型化对象,请尝试:

using Newtonsoft.Json;
// ...   
dynamic json  = JsonConvert.DeserializeObject(str);

或者尝试类型化对象,请尝试:

using Newtonsoft.Json;
// single    
Foo foo  = JsonConvert.DeserializeObject<Foo>(str);
// or as a list
List<Foo> foos = JsonConvert.DeserializeObject<List<Foo>>(str); 

这有效

    string str = "{ 'context_name': { 'lower_bound': 'value', 'pper_bound': 'value', 'values': [ 'value1', 'valueN' ] } }";
    JavaScriptSerializer j = new JavaScriptSerializer();
    object a = j.Deserialize(str, typeof(object));
有一种

有趣的方法可以实现另一个目标,即使用我几天前第一次使用的非常强大的工具在 JSON 上拥有一个强类型类,将 Tradedoubler JSON 结果转换为类

是一个简单的工具:复制您的 json 源粘贴,几秒钟后您将拥有一个面向 json 的强类型类。通过这种方式,您将使用这些更强大且易于使用的类。

您可以尝试如下:

string output = JsonConvert.SerializeObject(jsonStr);

使用JsonConvert对我有用

var result = JsonConvert.DeserializeObject<Class>(responseString);

如果您的 JSon 字符串有 " 双引号而不是单引号 ' 并且有 ' 作为下一行的指示符,那么您需要删除它,因为这不是正确的 JSon 字符串,示例如下所示:

            SomeClass dna = new SomeClass ();
            string response = wc.DownloadString(url);
            string strRemSlash = response.Replace("'"", "''");
            string strRemNline = strRemSlash.Replace("'n", " ");
            // Time to desrialize it to convert it into an object class.
            dna = JsonConvert.DeserializeObject<SomeClass>(@strRemNline);
在从

API 检索特定实体的对象列表的情况下,响应字符串可能如下所示:

[{"id":1,"nome":"eeee","username":null,"email":null},{"id":2,"nome":"eeee","username":null,"email":null},{"id":3,"nome":"Ricardo","username":null,"email":null}]

在这种情况下,您可能需要一个 Jason 对象数组,并在它们之间循环以填充 c# 变量。我这样做了:

var httpResponse = await Http.GetAsync($"api/{entidadeSelecionada}");
    List<List<string[]>> Valores = new();
    if (httpResponse.IsSuccessStatusCode)
    {
        //totalPagesQuantity = int.Parse(httpResponse.Headers.GetValues("pagesQuantity").FirstOrDefault());
        //Aqui tenho que colocar um try para o caso de ser retornado um objecto vazio
        var responseString = await httpResponse.Content.ReadAsStringAsync();
        JArray array = JArray.Parse(responseString);
        foreach (JObject objx in array.Children<JObject>())
        {
            List<string[]> ls = new();
            foreach (JProperty singleProp in objx.Properties())
            {
                if (!singleProp.Name.Contains("_xyz"))
                {
                    string[] val = new string[2];
                    val[0] = singleProp.Name;
                    val[1] = singleProp.Value.ToString();
                    ls.Add(val);
                }
            }
            Valores.Add(ls);
        }
    }
    return Valores;

我通过@Andrei答案实现了这个解决方案。

这在

JObject 的情况下不起作用,这适用于简单的 json 格式数据。我已经尝试了以下 json 格式数据的数据在类型中反序列化,但没有得到响应。

对于这个杰森

{
  "Customer": {
    "id": "Shell",
    "Installations": [
      {
        "id": "Shell.Bangalore",
        "Stations": [
          {
            "id": "Shell.Bangalore.BTM",
            "Pumps": [
              {
                "id": "Shell.Bangalore.BTM.pump1"
              },
              {
                "id": "Shell.Bangalore.BTM.pump2"
              },
              {
                "id": "Shell.Bangalore.BTM.pump3"
              }
            ]
          },
          {
            "id": "Shell.Bangalore.Madiwala",
            "Pumps": [
              {
                "id": "Shell.Bangalore.Madiwala.pump4"
              },
              {
                "id": "Shell.Bangalore.Madiwala.pump5"
              }
            ]
          }
        ]
      }
    ]
  }
}
string result = await resp.Content.ReadAsStringAsync();
            List<ListView11> _Resp = JsonConvert.DeserializeObject<List<ListView11>>(result);
            //List<ListView11> _objList = new List<ListView11>((IEnumerable<ListView11>)_Resp);
            IList usll = _Resp.Select(a => a.lttsdata).ToList();
            // List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
            //IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
            Lv.ItemsSource = usll;