简体   繁体   中英

Deserialize Json into a C# Object

I am aware this topic has been previously posted. But I tried following them. However, my result is still not being shown. I would appreciate any help possible. Thanks in advance. :) I am getting the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.'

I am trying to deserialize a JSON object into ac# object to output the property score.

My Json output from json = toneAnalyzer.Tone(toneInput) :

{
  "document_tone" : {
    "tones" :
      [
        {
          "score" : 0.70123,
          "tone_id" : "tentative",
          "tone_name" : "Tentative"
        }
      ]
    }
}

I have carried out the following code:

    var json = toneAnalyzer.Tone(toneInput); // this is my json source

    DocTone myResult = new DocTone();
    myResult = JsonConvert.DeserializeObject<DocTone>(json.Response);

    foreach (var myTone in myResult.tones)
    {
        Console.Write(myTone.Score);
        Console.ReadKey();
    }


    //  Console.WriteLine(myResult);
    //  Console.WriteLine(result.Response);

}

public class MyTone1
{ 
    [JsonProperty("score")]
    public double Score { get; set; }

    [JsonProperty("tone_id")]
    public string Tone_Id { get; set; }

    [JsonProperty("tone_name")]
    public string Tone_Name { get; set; }
}

public class DocTone
{
    [JsonProperty("tones")]
    public List<MyTone1> tones { get; set; }
}

You've got a slight mistake with the object you are deserialising to.

Your root object is not DocTone , but actually the object that has a property containing the DocTone object (via the document_tone element).

Define a root object (call it whatever you like) and then deserialise to that:

public class RootObject
{
    [JsonProperty("document_tone")]
    public DocTone DocTone { get; set; }
}

Deserialise and then access via the DocTone property:

RootObject myResult;
myResult = JsonConvert.DeserializeObject<RootObject>(json.Response);

foreach (var myTone in myResult.DocTone.tones)
    ...

The reason that you are experiencing the NullReferencException is because when you deserialise to a DocTone object, the tones property is NULL .

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