简体   繁体   English

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

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

I have a code REST API response which is json, and parsing to JObject and pulling a value from it. 我有一个代码REST API响应,它是json,并解析为JObject并从中提取一个值。 But i am getting the error when parsing to JObject. 但是我在解析到JObject时遇到错误。

Error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0." 错误:“解析值:S.Path时遇到意外字符,行0,位置0。”

Is there any other way to convert Json string to C# object. 还有其他方法可以将Json字符串转换为C#对象。

I have the following code: using Newtonsoft.Json; 我有以下代码:使用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"];
        }                                      

    }

} }

I am expecting the value from (String)responseObject["enteries"]["content"][" properties"]["object_name"] 我期望来自(String)responseObject [“ enteries”] [“ content”] [“ properties”] [“ object_name”]的值

JObjects are a pain. JObjects很痛苦。 You could get a sample of the JSON response and paste it into a converter like json2csharp.com. 您可以获取JSON响应的样本并将其粘贴到json2csharp.com之类的转换器中。 It will generate a class for you which you can then use like so: 它将为您生成一个类,您可以像这样使用它:

Generated Class: 生成的类:

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

Usage: 用法:

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

I would suggest to follow those steps: 我建议遵循以下步骤:

  1. You need to check that your json is actually a json , because an error says it is not. 您需要检查您的json实际上是json ,因为错误表明不是。 You can use online tools like this 您可以使用像这样的在线工具
  2. If possible, avoid JObject and generate real classes. 如果可能,请避免使用JObject并生成真实的类。 It is not that hard if you know the structure, and you can use another online tools 如果您知道其结构并不难,可以使用其他在线工具
  3. Modify your code to use classes 修改您的代码以使用类

so you will have something like: 因此您将获得类似以下内容的信息:

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

I hope it helps 😊 希望对您有帮助

Using Newtonsoft.Json 使用Newtonsoft.Json

First get the list of entries from the responseObj . 首先从responseObj获取条目列表。 Then loop each entries and use LINQ to JSON to get values by property name or index. 然后循环每个条目,并使用LINQ to JSON通过属性名称或索引获取值。

You can use Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want 您可以在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"];
}

Thank you so much for all the help and trips. 非常感谢您提供的所有帮助和旅行。 Finally i am able to get the required value from JSON string. 最后,我能够从JSON字符串中获取所需的值。

Here is the Final code json2csharp.com 这是最终代码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