Home > Software engineering >  Asp .Net Core Json deserialize to model
Asp .Net Core Json deserialize to model

Time:04-05

Returns Json format data to me from an api.

However, the type of the "FuelType" property inside the object may be different. For example, 1 time comes as follows:

{
...
fuelType: "gasoline"
...
}}

But then it can happen:

{
...
fuelType: ["gasoline", "any"]
...
}}

If I set the "FuelType" property type on my model to a string, in the second case, Json will give me an error when it arrives, because it can't convert from array to string. No, if I set the type to an array, then, conversely, if a string arrives, it will issue an error because it cannot convert from a string to an array.

In this case, what should I put the "FuelType" property type in my model so that it does not make an error when deserializing?

CodePudding user response:

try this

var fuelType = JsonConvert.DeserializeObject<MyClass>(json);

public class MyClass
{
    [JsonProperty("fuelType")]
    private JToken _fuelType;

    [JsonIgnore]
    public string[] fuelType
    {
        get { return _fuelType is JArray ? _fuelType.ToObject<string[]>() : new string[] { (string)_fuelType }; }
    }
}

CodePudding user response:

It all depends on you,what type of value you want to receive?string or List?

I tried with the codes:

public class SomeModel
    {
        public SomeModel()
        {
            fuelType = new List<string>();            
        }
        public int Id { get; set; }
        public string  Name { get; set; }
        
        public List<string> fuelType { get; set; }

        //you could move the codes to someservice
        public List<string> someresult(string a)
        {
            var targetlist = new List<string>();
            targetlist.Add(a);
            return targetlist;
        }
        public List<string> someresult(List<string> a)
        {
            var targetlist = new List<string>();
            targetlist.AddRange(a);
            return targetlist;
        }
    }

[HttpPost]
        public JsonResult SomeAction()
        {
            var somemodel = new SomeModel() { Id = 1, Name = "name" };
            var somevalue = /*"a"*/new List<string>() { "a", "b", "c" };
            var targetvalue = somemodel.someresult(somevalue);
            somemodel.fuelType.AddRange(targetvalue);
            return new JsonResult(somemodel);
        }

Result: enter image description here

  • Related