0

I know it's probably very trivial question but I can't seem to find an answer online..

Imagine I have a below JSON

{"userId" : "myUser","sites" : ["site1", "site2"] }

I would like to parse it to C# object User but RestSharp parser is failing to parse array correctly. I tried implementing sites as below:

public string[] sites = new string[5];

public List<string> sites;

but nothing seems to work.

For deserialization I use

JsonDeserializer deserial = new JsonDeserializer();

User newUser = new User();

newUser = deserial.Deserialize<user>(response); --> response is a IRestResponse object.

The code is correctly parsing the simple strings like userId but it's struggling with arrays...

What I am doing wrong? Is RestSharp not the right tool to do that?

What in case the is an object array in Json like

{"userImgs" : {"small": "https://myImage.co.uk/small", "large" : "https://myImage.co.uk/large"}}

Could I just have an object with an object as property an would the parser handle that if I implemented my class as below?

Class User{

string userId;

UserImages userImg = new UserImages();

Thanks

aberforth
  • 72
  • 11
  • I think you are basically on the right track, and it's most likely a mismatch of the property name (sites) and what's actually in the JSON. Can you inspect the "IRestResponse" and see what the actual json is and include it? – Daniel James Bryars Feb 13 '21 at 13:13
  • @DanielJamesBryars - I basically copy-pasted my attributes from Json using Postman. And I also checked the names to be sure they are the same and they are... I'm sure of it – aberforth Feb 13 '21 at 13:24
  • I hope this will help you: [comment](https://stackoverflow.com/a/16157322/8978576) – Serhii Feb 13 '21 at 14:47

1 Answers1

2

I would recommend using newtonsoft.

    using Newtonsoft.Json;
    class User
    {
        public string userId { get; set; }
        public List<string> sites { get; set; }
    }
    static void Main(string[] args)
    {
        string response = "{\"userId\" : \"myUser\",\"sites\" : [\"site1\", \"site2\"] }";
        User obj = JsonConvert.DeserializeObject<User>(response);
    }
Vivek Raj
  • 85
  • 7
  • yeah, That's fine but I started using RestSharp and I bet there is a way to achieve this without adding new libraries. – aberforth Feb 13 '21 at 13:23