简体   繁体   中英

Deserialization Issue by Newtonsoft

I want to deserilize this Json to Model, this is the Json: [{"dimensions": [ "www "], "metrics ": [{ "values ": [ "2 " ]},{ "values ": [ "0 "]}]}]

and i create this model to deserialize json to this model:

public class ResultModel
{
    public List<string> dimensions { get; set; }
    public List<Metric> metrics { get; set; }
}

and

public class Metric
{
    public List<string> values { get; set; }
}

and using Newtonsoft for this:

 var model = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultModel>(json);

but it doesnot work and give me this error:

'Cannot deserialize the current JSON array (eg [1,2,3]) into type 'ResultModel' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly'.

What is the problem?

It's easy to miss that your JSON is really array, even if it contains just one object. So you have to deserialize it to array:

var model = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultModel[]>(json);

If you're sure that there will be at most one model, you can do:

var model = JsonConvert.DeserializeObject<IEnumerable<ResultModel>>(json).FirstOrDefault();

Otherwise, you should deserialize it to a collection of models, as suggested in the comments:

// models is an IEnumerable<ResultModel>
var models = JsonConvert.DeserializeObject<IEnumerable<ResultModel>>(json);

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