shahram kalantari
shahram kalantari

Reputation: 863

Parsing a JArray object in C#

I have a JArray object named as response whose value is:

{[
  {"alternatives": [
      {
       "transcript": "some text",
       "confidence": 0.77053386
      }
    ]
  },
  {"alternatives": [
      {
       "transcript": " some other text",
       "confidence": 0.84036005
      }
    ]
  }
]}

I'm trying to access the transcript values and concatenate them together. This is my code:

 var results = response.ToObject<IList<Alternatives>>();
 string mostConfidentTranscript = "";
 foreach (var r in results)
      mostConfidentTranscript += r.transcript + "\n";

Where Alternatives class is defined as:

public class Alternatives
{
    public double confidence { get; set; }
    public string transcript { get; set; }
}

The code compiles with no errors, however, results is an empty list. What am I missing? Any help is appreciated.

Upvotes: 1

Views: 3186

Answers (2)

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

The JSON provided isn't valid. A little modification , and this is what worked for me -

public class Alternative
{
    public double confidence { get; set; }
    public string transcript { get; set; }
}

public class RootObject{
    public List<Alternative> Alternatives{get;set;}
}

var json = "[{'alternatives':[{'transcript':'some text','confidence':0.77053386}]},{'alternatives':[{'transcript':' some other text','confidence':0.84036005}]}]";
var res = JsonConvert.DeserializeObject<List<RootObject>>(json);
// output : "some text: some other text"
Console.WriteLine(res[0].Alternatives[0].transcript + ":" + res[1].Alternatives[0].transcript);

Upvotes: 0

Fan Ouyang
Fan Ouyang

Reputation: 2142

payload is not right, if you mean post a list of object, better to change to:

{"value":[...]}

then you can read this as a JObject, and get the value as JArray.

using Newtonsoft.Json.Linq;

result = response.Content.ReadAsAsync<JObject>().Result;
var results = result["value"] as JArray;

Upvotes: 1

Related Questions