简体   繁体   中英

.net json deserializer failing for google api returned json result

I am unable to deserialize the json result I am getting from google api during an API call. The API request is successful, but I can't deserialize it.

Code for deserialization is as follows :

var datareceived = JsonConvert.DeserializeObject<RootObject>(response);

Please find below the json I am getting from Google api(response object in above code) :

{"result":[]}
{"result":[{"alternative":[{"transcript":"distance between the trees","confidence":0.46962094},{"transcript":"Justin prescription that reason"},{"transcript":"Justin Swift accessories"},{"transcript":"justice respiratory"},{"transcript":"Justin syska accessories"}],"final":true}],"result_index":0}

Exception Details :

Message = "Additional text encountered after finished reading JSON content: {. Path '', line 2, position 0."

RootObject Class :

public class RootObject
{
    public List<Result> result { get; set; }
    public int result_index { get; set; }
}

Any help would be highly appreciated!

You can utilize following method to get JSON in List:

public List<string> GetJsonItems(string jsonString)
{
    int bracketCount = 0;
    List<string> jsonItems = new List<string>();
    StringBuilder Json = new StringBuilder();

    foreach (char c in jsonString)
    {
        if (c == '{')
            ++bracketCount;
        else if (c == '}')
            --bracketCount;
        Json.Append(c);

        if (bracketCount == 0 && c != ' ')
        {
            jsonItems.Add(Json.ToString());
            Json = new StringBuilder();
        }
    }
    return jsonItems;
}

Then utilize it like:

List<string> strings = GetJsonItems(response.Replace(Environment.NewLine, String.Empty));

if (strings.Length > 1)
{
    List<Rootobject> allResultSet = new List<Rootobject>();
    foreach (var str in strings)
    {
        Rootobject items = JsonConvert.DeserializeObject<Rootobject>(str);
        if (items.result.Length > 0)
        {
            allResultSet.Add(items);
        }
    }
}

you just can't parse this JSON as it is because } symbolize the end of JSON

but you can do something like this

string json = "{\"result\":[]}\r\n{\"result\":[{\"alternative\":[{\"transcript\":\"distance between the trees\",\"confidence\":0.46962094},{\"transcript\":\"Justin prescription that reason\"},{\"transcript\":\"Justin Swift accessories\"},{\"transcript\":\"justice respiratory\"},{\"transcript\":\"Justin syska accessories\"}],\"final\":true}],\"result_index\":0}";

string trueJson = json.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[1];
try
{
    RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(trueJson);
    rootObject = rootObject;
}
catch (Exception ex)
{      
    throw;
}

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

public class Result
{
    public List<Alternative> alternative { get; set; }
    public bool final { get; set; }
}

public class RootObject
{
    public List<Result> result { get; set; }
    public int result_index { get; set; }
}  

It seems that each line of the result contains a separate JSON object. (It's not clear why the API doesn't return an actual JSON array instead.) If this is the case, you can split the response into lines and parse each line separately:

string[] lines = response.Split(new char[]{'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
var datareceived1 = JsonConvert.DeserializeObject<RootObject>(lines[0]);

... and so on.

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