Loading JSON from URL with multiple items

tryingtolearn

Member
Joined
Mar 13, 2018
Messages
12
Programming Experience
Beginner
I'm very close to a solution and I think the problem is due to one line of code, but I can't figure out what I am doing wrong. I am using JSON.Net to load a JSON file from a specific URL. The JSON file has about 100 items. I've seen examples of deserialization with one item but not multiple. I need the JSON items to be deserialized into a list of objects. I've achieved the below by using examples I've found online. First, here is the JSON structure:

C#:
[
    {"Username":"some_username1","password":"some_password1"}
    {"Username":"some_username2","password":"some_password2"}
    {"Username":"some_username3","password":"some_password3"}
]

I have this class:

C#:
[COLOR=green]// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:[/COLOR]
[COLOR=green]//[/COLOR]
[COLOR=green]//    using ProgramUser;[/COLOR]
[COLOR=green]//[/COLOR]
[COLOR=green]//    var person = Person.FromJson(jsonString);[/COLOR]

[COLOR=blue]namespace[/COLOR] ProgramUser
{
    [COLOR=blue]using[/COLOR] System;
    [COLOR=blue]using[/COLOR] System.Collections.Generic;

    [COLOR=blue]using[/COLOR] System.Globalization;
    [COLOR=blue]using[/COLOR] Newtonsoft.Json;
    [COLOR=blue]using[/COLOR] Newtonsoft.Json.Converters;

    [COLOR=blue]public[/COLOR] [COLOR=blue]partial[/COLOR] [COLOR=blue]class[/COLOR] [COLOR=#2b91af]Person[/COLOR]
    {
        [[COLOR=#2b91af]JsonProperty[/COLOR]([COLOR=#a31515]"username"[/COLOR])]
        [COLOR=blue]public[/COLOR] [COLOR=blue]string[/COLOR] username { [COLOR=blue]get[/COLOR]; [COLOR=blue]set[/COLOR]; }
 
        [[COLOR=#2b91af]JsonProperty[/COLOR]([COLOR=#a31515]"password"[/COLOR])]
        [COLOR=blue]public[/COLOR] [COLOR=blue]string[/COLOR] password { [COLOR=blue]get[/COLOR]; [COLOR=blue]set[/COLOR]; }
 
 
    }

    [COLOR=blue]public[/COLOR] [COLOR=blue]partial[/COLOR] [COLOR=blue]class[/COLOR] [COLOR=#2b91af]Person[/COLOR]
    {
        [COLOR=blue]public[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=#2b91af]Person[/COLOR][] FromJson([COLOR=blue]string[/COLOR] json) => [COLOR=#2b91af]JsonConvert[/COLOR].DeserializeObject<[COLOR=#2b91af]Person[/COLOR][]>(json, GISv1.[COLOR=#2b91af]Converter[/COLOR].Settings);
    }

    [COLOR=blue]public[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]class[/COLOR] [COLOR=#2b91af]Serialize[/COLOR]
    {
        [COLOR=blue]public[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]string[/COLOR] ToJson([COLOR=blue]this[/COLOR] [COLOR=#2b91af]Person[/COLOR][] self) => [COLOR=#2b91af]JsonConvert[/COLOR].SerializeObject(self, GISv1.[COLOR=#2b91af]Converter[/COLOR].Settings);
    }

    [COLOR=blue]internal[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]class[/COLOR] [COLOR=#2b91af]Converter[/COLOR]
    {
        [COLOR=blue]public[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]readonly[/COLOR] [COLOR=#2b91af]JsonSerializerSettings[/COLOR] Settings = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]JsonSerializerSettings[/COLOR]
        {
            MetadataPropertyHandling = [COLOR=#2b91af]MetadataPropertyHandling[/COLOR].Ignore,
            DateParseHandling = [COLOR=#2b91af]DateParseHandling[/COLOR].None,
            Converters = {
                [COLOR=blue]new[/COLOR] [COLOR=#2b91af]IsoDateTimeConverter[/COLOR] { DateTimeStyles = [COLOR=#2b91af]DateTimeStyles[/COLOR].AssumeUniversal }
            },
        };
    }
}


When I try to create an instance of the above class, I am getting errors.

C#:
[COLOR=blue]namespace[/COLOR] ProgramUser
{
    [COLOR=blue]public[/COLOR] [COLOR=blue]partial[/COLOR] [COLOR=blue]class[/COLOR] [COLOR=#2b91af]Form1[/COLOR] : [COLOR=#2b91af]Form[/COLOR]
    {
        [COLOR=blue]public[/COLOR] [COLOR=#2b91af]List[/COLOR]<[COLOR=#2b91af]Person[/COLOR]> lstPeople = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]List[/COLOR]<[COLOR=#2b91af]Person[/COLOR]>();
 
        [COLOR=blue]public[/COLOR] Form1()
        {
            InitializeComponent();
        }
 
        [COLOR=blue]private[/COLOR] [COLOR=blue]void[/COLOR] getUsersFromURL()
        {
   [COLOR=blue]       var[/COLOR] res= _download_serialized_json_data<[COLOR=#2b91af]Person[/COLOR]>("EXAMPLE.DOM/USERS.JSON");

        }
 
      [COLOR=blue]private[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=#2b91af]T[/COLOR] _download_serialized_json_data<[COLOR=#2b91af]T[/COLOR]>([COLOR=blue]string[/COLOR] url) [COLOR=blue]where[/COLOR] [COLOR=#2b91af]T[/COLOR] : [COLOR=blue]new[/COLOR]()
        {
            [COLOR=blue]using[/COLOR] ([COLOR=blue]var[/COLOR] w = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]WebClient[/COLOR]())
            {
                [COLOR=blue]var[/COLOR] json_data = [COLOR=blue]string[/COLOR].Empty;
                [COLOR=green]// attempt to download JSON data as a string[/COLOR]
                [COLOR=blue]try[/COLOR]
                {
                    json_data = w.DownloadString(url);
                    [COLOR=green]//loop through each line and create an object of "Person" and add it to list[/COLOR]
                    [COLOR=blue]using[/COLOR] ([COLOR=#2b91af]StringReader[/COLOR] reader = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]StringReader[/COLOR](json_data))
                    {
                        [COLOR=blue]string[/COLOR] line;
                        [COLOR=blue]while[/COLOR] ((line = reader.ReadLine()) != [COLOR=blue]null[/COLOR])
                        {
                           [COLOR=blue]            var[/COLOR] personToAdd =  [COLOR=#2b91af]Person[/COLOR].FromJson(line);
                          lstPeople.Add(personToAdd);
                        }
                    }
                }
                [COLOR=blue]catch[/COLOR] ([COLOR=#2b91af]Exception[/COLOR]) { }
                [COLOR=green]// if string with JSON data is not empty, deserialize it to class and return its instance [/COLOR]
                [COLOR=blue]return[/COLOR] ![COLOR=blue]string[/COLOR].IsNullOrEmpty(json_data) ? [COLOR=#2b91af]JsonConvert[/COLOR].DeserializeObject<[COLOR=#2b91af]T[/COLOR]>(json_data) : [COLOR=blue]new[/COLOR] [COLOR=#2b91af]T[/COLOR]();
            }
        }
 
    }
}


I am getting an error at " People.Add(personToAdd)" It will not let me create an instance of this. It says "Cannot convert ProgramUser.Person[] to ProgramUser.Person"

I'm at a loss here. Any suggestions are greatly appreciated.

Thank you,
Rob
 
I found a solution if anyone encounters this problem:

C#:
[COLOR=blue]class[/COLOR][COLOR=#0b0117] Contact[/COLOR]
   {
       [COLOR=blue]public[/COLOR] [COLOR=blue]string[/COLOR] Username{ [COLOR=blue]get[/COLOR]; [COLOR=blue]set[/COLOR]; }
       [COLOR=blue]public[/COLOR] [COLOR=blue]string[/COLOR] Password{ [COLOR=blue]get[/COLOR]; [COLOR=blue]set[/COLOR]; }
   }
 
 
   [COLOR=blue]public[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]void[/COLOR] Main()
   {
       [COLOR=blue]string[/COLOR] json;
       [COLOR=blue]using[/COLOR] ([COLOR=blue]var[/COLOR] wc = [COLOR=blue]new[/COLOR] System.Net.[COLOR=#2b91af]WebClient[/COLOR]())
           json = wc.DownloadString([COLOR=#a31515]"example.com/users.json"[/COLOR]);
 
       [COLOR=blue]byte[/COLOR][] bytes = [COLOR=#2b91af]Encoding[/COLOR].UTF8.GetBytes(json);
 
       [COLOR=green]// replace the MemoryStream here with the InputStream from your web request[/COLOR]
       [COLOR=blue]using[/COLOR] ([COLOR=#2b91af]MemoryStream[/COLOR] stream = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]MemoryStream[/COLOR](bytes))
       [COLOR=blue]using[/COLOR] ([COLOR=#2b91af]StreamReader[/COLOR] sr = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]StreamReader[/COLOR](stream))
       [COLOR=blue]using[/COLOR] ([COLOR=#2b91af]JsonTextReader[/COLOR] reader = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]JsonTextReader[/COLOR](sr))
       {
           reader.SupportMultipleContent = [COLOR=blue]true[/COLOR];
 
           [COLOR=blue]var[/COLOR] serializer = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]JsonSerializer[/COLOR]();
           [COLOR=blue]while[/COLOR] (reader.Read())
           {
               [COLOR=blue]if[/COLOR] (reader.TokenType == [COLOR=#2b91af]JsonToken[/COLOR].StartObject)
               {
                   [COLOR=#2b91af]Contact[/COLOR] c = serializer.Deserialize<[COLOR=#2b91af]Contact[/COLOR]>(reader);
                   [COLOR=#2b91af]Console[/COLOR].WriteLine(c.username + [COLOR=#a31515]" "[/COLOR] + c.password);
               }
           }
       }
       [COLOR=#2b91af]Console[/COLOR].ReadLine();
   }
 

Latest posts

Back
Top Bottom