繁体   English   中英

将Rest API JSON响应转换为C#对象

[英]Convert Rest API JSON Response into C# object

我有一个代码REST API响应,它是json,并解析为JObject并从中提取一个值。 但是我在解析到JObject时遇到错误。

错误:“解析值:S.Path时遇到意外字符,行0,位置0。”

还有其他方法可以将Json字符串转换为C#对象。

我有以下代码:使用Newtonsoft.Json;

    using (HttpResponseMessage message = httpclient.GetAsync(folderIdURL).Result)
    {
        if(message.IsSuccessStatusCode)
        {
            var dataobjects = message.Content.ReadAsStringAsync();
            //dataobjects = "{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/","title":"DQL query results","author":[{"name":"EMC Documentum"}],"updated":"2019-05-02T15:19:52.508+00:00","page":1,"items-per-page":100,"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)"}],"entries":[{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=0","title":"0b0111738011c114","updated":"2019-05-02T15:19:52.508+00:00","published":"2019-05-02T15:19:52.508+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositori                      es/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c114","object_name":"04"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}]}},{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=1","title":"0b0111738011c115","updated":"2019-05-02T15:19:52.509+00:00","published":"2019-05-02T15:19:52.509+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c115","object_name":"05"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}]}}]}"

            JObject responseObj = JObject.Parse(dataobjects.ToString());
            String id = (String)responseObj["entries" -->"content"-->"properties"-->"object_name"];
        }                                      

    }

}

我期望来自(String)responseObject [“ enteries”] [“ content”] [“ properties”] [“ object_name”]的值

JObjects很痛苦。 您可以获取JSON响应的样本并将其粘贴到json2csharp.com之类的转换器中。 它将为您生成一个类,您可以像这样使用它:

生成的类:

public class MyClass
{
    public string SomeProperty { get; set; }
    public string AnotherProperty { get; set; }
}

用法:

if (message.IsSuccessStatusCode)
{
     var deserializedObject = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result);
     Console.WriteLine(deserializedObject.SomeProperty);
}

我建议遵循以下步骤:

  1. 您需要检查您的json实际上是json ,因为错误表明不是。 您可以使用像这样的在线工具
  2. 如果可能,请避免使用JObject并生成真实的类。 如果您知道其结构并不难,可以使用其他在线工具
  3. 修改您的代码以使用类

因此您将获得类似以下内容的信息:

using System;
using Newtonsoft.Json;

namespace ConsoleApp11
{
    class Program
    {
        public class Message
        {
            public Enteries enteries { get; set; }
        }
        public class Enteries
        {
            public Content content { get; set; }
        }
        public class Content
        {
            public Properties properties { get; set; }
        }
        public class Properties
        {
            public string object_name { get; set; }
        }

        static void Main(string[] args)
        {
            var input = "{\"enteries\":{\"content\":{ \"properties\":{ \"object_name\":\"your value string\"}}}}";
            Message msg = JsonConvert.DeserializeObject<Message>(input);
            Console.WriteLine(msg?.enteries?.content?.properties?.object_name ?? "no value");
            Console.ReadKey();
        }
    }
}

希望对您有帮助

使用Newtonsoft.Json

首先从responseObj获取条目列表。 然后循环每个条目,并使用LINQ to JSON通过属性名称或索引获取值。

您可以在JObject / JArray上使用Item[Object]索引,然后将返回的JValue强制转换为所需的类型

JObject responseObj = JObject.Parse(dataobjects.ToString());

// get JSON result objects into a list
IList<JToken> entries = responseObj ["entries"].Children().ToList();

foreach(JToken entry in entries)
{
    string object_name = (string) entry["content"]["properties"]["object_name"];
}

非常感谢您提供的所有帮助和旅行。 最后,我能够从JSON字符串中获取所需的值。

这是最终代码json2csharp.com

public class Author
{
    public string name { get; set; }
}

public class Link
{
    public string rel { get; set; }
    public string href { get; set; }
}

public class Link2
{
    public string rel { get; set; }
    public string href { get; set; }
}

public class Properties
{
    public string r_object_id { get; set; }
    public string object_name { get; set; }
}

public class Link3
{
    public string rel { get; set; }
    public string href { get; set; }
}

public class Content
{
    public string json_root { get; set; }
    public string definition { get; set; }
    public Properties properties { get; set; }
    public List<Link3> links { get; set; }
}

public class Entry
{
    public string id { get; set; }
    public string title { get; set; }
    public DateTime updated { get; set; }
    public DateTime published { get; set; }
    public List<Link2> links { get; set; }
    public Content content { get; set; }
}

public class RootObject
{
    public string id { get; set; }
    public string title { get; set; }
    public List<Author> author { get; set; }
    public DateTime updated { get; set; }
    public int page { get; set; }
    public int items_per_page { get; set; }
    public List<Link> links { get; set; }
    public List<Entry> entries { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM