简体   繁体   中英

weird Object reference not set to an instance of an object?

I'm pretty new to C#, i have this code:

downloads obj = JsonConvert.DeserializeObject<downloads>(data);

foreach (KeyValuePair<string, client> kvp in obj.client)
{
    Console.WriteLine("URL: " + kvp.Value.url);
    Console.WriteLine("SHA1: " + kvp.Value.sha1);
    matrix[0].Add(kvp.Value.url);
    matrix[0].Add(kvp.Value.sha1);
}

with these classes:

class downloads
{
    [JsonProperty("client")]
    public Dictionary<string, client> client { get; set; }
}

class client
{
    [JsonProperty("url")]
    public string url { get; set; }
    [JsonProperty("sha1")]
    public string sha1 { get; set; }
}

It says me Object reference not set to an instance of an object but how can i create a reference and use that reference as a type? I mean, i create a reference to downloads this say:

downloads down = new downloads();

but now how can i assign a variable that json deserialize? here is the complete code: https://dotnetfiddle.net/F9mSvQ

Partial JSON:

{ 
"downloads": 
  {
    "client": { "sha1": "e80d9b3bf5085002218d4be59e668bac718abbc6" },
    "server": { "sha1": "952438ac4e01b4d115c5fc38f891710c4941df29" }
   }
 }

From the JSON downloads itself should be dictionary on Client objects OR contain several properties of type Client like

class Downloads
{
  public Client client { get; set; }
  public Client server { get; set; }
}

Debugging note: It is always good idea to serialize your class to see what result it produces - this would let you know if structure looks matching or not.

First of all, I suggest you to stick to traditional Naming Conventions

It will help you and others to see your code better and more clear.

Based on the class structure you have, here is the json format that you want.

string json = @"{clients: {
     'clientname1':{'sha1':'shahashhere','url':'urlhere'},
     'clientname2':{'sha1':'shahashhere','url':'urlhere'}
 }}";

Change the values as needed.

Here is link to the https://dotnetfiddle.net/uedQ8i . I changed the classes name as I was confused while I was working on it.

EDIT

Since OP doesn't have control of JSON string, then another class have to be made to contain downloads object

class MinecraftObject {
    Downloads downloads {get;set;}
}

Deserializing the json string

var obj = JsonConvert.DeserializeObject<MinecraftObject>(json);
var download = obj.downloads;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM