Convert Rest API JSON Response into C# object

浪子不回头ぞ 提交于 2019-12-24 23:24:23

问题


I have a code REST API response which is json, and parsing to JObject and pulling a value from it. But i am getting the error when parsing to JObject.

Error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."

Is there any other way to convert Json string to C# object.

I have the following code: using 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"]


回答1:


JObjects are a pain. You could get a sample of the JSON response and paste it into a converter like 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);
}



回答2:


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. You can use online tools like this
  2. If possible, avoid JObject and generate real classes. 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 😊




回答3:


Using Newtonsoft.Json

First get the list of entries from the responseObj. Then loop each entries and use LINQ to JSON to get values by property name or index.

You can use Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want

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



回答4:


Thank you so much for all the help and trips. Finally i am able to get the required value from JSON string.

Here is the Final code 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; }
}


来源:https://stackoverflow.com/questions/55956529/convert-rest-api-json-response-into-c-sharp-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!