Cannot parse Json

Yusuf 751 Reputation points
2021-03-07T14:45:32.66+00:00
using System;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
public class Program
{
    public static void Main()
    {


                    string apiUrl = @"https://api.unsplash.com/photos/random?count=10&collections=83552409&client_id=CY4AxNv4zE9Unv0QLIHzCb8t5GCHQ_LgKUhqtMoQ-G0";

                    WebClient webclient = new WebClient();
                    webclient.Encoding = Encoding.UTF8; 

                    string jsonString = webclient.DownloadString(apiUrl);

                    JObject jObj = JObject.Parse(jsonString);    

                    Console.WriteLine( (string)jObj["1"]["urls"]["full"]);



    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,604 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.4K Reputation points
    2021-03-07T15:24:29.343+00:00

    The quick solution is:

    JObject jObj = JObject.Parse( "{\"root\": " + jsonString + "}" );
    Console.WriteLine( (string)jObj["root"][1]["urls"]["full"] );
    

    You can also consider other approaches, which maybe are more appropriate from some points of view.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Mattias Asplund 236 Reputation points
    2021-03-07T15:04:18.18+00:00

    I took the following steps to accomplish this task:

    1) Converted the Json payload to C# classes using https://json2csharp.com (there are several sites out there that can do the same)
    2) Embedded the classes in Program.cs (to be easily overviewed)
    3) Used JsonSerializer from System.Text to do the deserialization, instead of Newtonsoft.

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Text;
    using System.Text.Json;
    
    namespace ParseJson
    {
        class Program
        {
            static void Main(string[] args)
            {
                string apiUrl = @"https://api.unsplash.com/photos/random?count=10&collections=83552409&client_id=CY4AxNv4zE9Unv0QLIHzCb8t5GCHQ_LgKUhqtMoQ-G0";
                WebClient webclient = new WebClient();
                webclient.Encoding = Encoding.UTF8;
                string jsonString = webclient.DownloadString(apiUrl);
                var obj = JsonSerializer.Deserialize<Root[]>(jsonString);
                Console.WriteLine(obj[0].urls.full);
            }
        }
        public class Urls
        {
            public string raw { get; set; }
            public string full { get; set; }
            public string regular { get; set; }
            public string small { get; set; }
            public string thumb { get; set; }
        }
    
        public class Links
        {
            public string self { get; set; }
            public string html { get; set; }
            public string download { get; set; }
            public string download_location { get; set; }
            public string photos { get; set; }
            public string likes { get; set; }
            public string portfolio { get; set; }
            public string following { get; set; }
            public string followers { get; set; }
        }
    
        public class ProfileImage
        {
            public string small { get; set; }
            public string medium { get; set; }
            public string large { get; set; }
        }
    
        public class User
        {
            public string id { get; set; }
            public DateTime updated_at { get; set; }
            public string username { get; set; }
            public string name { get; set; }
            public string first_name { get; set; }
            public string last_name { get; set; }
            public string twitter_username { get; set; }
            public string portfolio_url { get; set; }
            public string bio { get; set; }
            public string location { get; set; }
            public Links links { get; set; }
            public ProfileImage profile_image { get; set; }
            public string instagram_username { get; set; }
            public int total_collections { get; set; }
            public int total_likes { get; set; }
            public int total_photos { get; set; }
            public bool accepted_tos { get; set; }
            public bool for_hire { get; set; }
        }
    
        public class Exif
        {
            public string make { get; set; }
            public string model { get; set; }
            public string exposure_time { get; set; }
            public string aperture { get; set; }
            public string focal_length { get; set; }
            public int? iso { get; set; }
        }
    
        public class Position
        {
            public double? latitude { get; set; }
            public double? longitude { get; set; }
        }
    
        public class Location
        {
            public string title { get; set; }
            public string name { get; set; }
            public string city { get; set; }
            public string country { get; set; }
            public Position position { get; set; }
        }
    
        public class Root
        {
            public string id { get; set; }
            public DateTime created_at { get; set; }
            public DateTime updated_at { get; set; }
            public DateTime? promoted_at { get; set; }
            public int width { get; set; }
            public int height { get; set; }
            public string color { get; set; }
            public string blur_hash { get; set; }
            public string description { get; set; }
            public string alt_description { get; set; }
            public Urls urls { get; set; }
            public Links links { get; set; }
            public List<object> categories { get; set; }
            public int likes { get; set; }
            public bool liked_by_user { get; set; }
            public List<object> current_user_collections { get; set; }
            public object sponsorship { get; set; }
            public User user { get; set; }
            public Exif exif { get; set; }
            public Location location { get; set; }
            public int views { get; set; }
            public int downloads { get; set; }
        }
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Karen Payne MVP 35,376 Reputation points
    2021-03-07T15:24:42.883+00:00

    Here is a modified version that is strongly typed.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Text;  
    using Newtonsoft.Json;  
      
      
    namespace ConsoleApp2  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                string apiUrl =   
                    "https://api.unsplash.com/photos/random?count=10" +   
                    "&collections=83552409&client_id=CY4AxNv4zE9Unv0QLIHzCb8t5GCHQ_LgKUhqtMoQ-G0";  
      
                WebClient webclient = new WebClient {Encoding = Encoding.UTF8};  
      
                string jsonString = webclient.DownloadString(apiUrl);  
      
                var firstItem = JsonConvert.DeserializeObject<List<UnSplashItem>>(jsonString).FirstOrDefault();  
                Console.WriteLine($"   Full: {firstItem?.urls.full}");  
                Console.WriteLine($"    Raw: {firstItem?.urls.raw}");  
                Console.WriteLine($"Regular: {firstItem?.urls.regular}");  
      
      
                Console.WriteLine();  
                Console.ReadLine();  
            }  
        }  
      
        public class UnSplashItem  
        {  
            public Urls urls { get; set; }  
        }  
      
        public class Urls  
        {  
            public string raw { get; set; }  
            public string full { get; set; }  
            public string regular { get; set; }  
            public string small { get; set; }  
            public string thumb { get; set; }  
        }  
      
    }  
      
    

    75134-f1.png

    1 person found this answer helpful.
    0 comments No comments