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

时间:2019-05-02 16:19:17

标签: c# json json.net

我有一个代码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”]中的值

4 个答案:

答案 0 :(得分:3)

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 :(得分:1)

我建议遵循以下步骤:

  1. 您需要检查您的json实际上是json,因为错误表明不是。您可以在线使用tools like this
  2. 如果可能,请避免使用JObject并生成真实的类。如果您知道结构并不难,则可以使用another online tools
  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();
        }
    }
}

我希望对您有帮助

答案 2 :(得分:0)

使用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"];
}

答案 3 :(得分:0)

非常感谢您提供的所有帮助和旅行。最终,我能够从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; }
}