簡體   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