Search code examples
c#jsonmvvmjson-deserialization

How to deserialize JSON using Newtonsoft Deserialize C#


I am trying to deserialize JSON file and want to assign to object ScanResult. var text showing all the values but scanresult showing null some null values. https://gyazo.com/ff2ce386f845394c458a88d43a1f30d8

please suggest if I am missing something. //MY jSon File SCAN Test 1-1543045410222.json 's code

{
    "at": 1543045410222,
    "i": 1000,
    "s": {
        "Sensor1": ["OFF"],
        "Sensor2": ["OFF"],
        "DataReady1": ["OFF"],
        "DataReady2": ["OFF"],
        "CV1": [5.0],
        "CV2": [6.0]
    }
}




 //ViewModel Code is as below:

public void ResendScanResult()
    {
        var ScanActivities = scanActivityManager.GetAll();
        foreach (var item in ScanActivities)
        {
            var scanName = item.ScanName;
            var dir = _dataFilePath + scanName + "\\";
            var jsonFileName = string.Format("{0}{1}-{2}.json", dir, scanName, item.ScanDateEpoch);
            string fileName = Path.GetFileName(jsonFileName);
            // ScanResult scanResult = new ScanResult();
            var text = File.ReadAllText(jsonFileName);
            //var scanResults = JsonConvert.DeserializeObject<ScanResult>(text);
            Common.Model.ScanResult scanResult = JsonConvert.DeserializeObject<Common.Model.ScanResult>(text);


            var Mvm = MonitorViewModel.Instance;
            //  TargetProvider target = Mvm.GetTargetProvider(scanResult);
            //  Mvm.PublishToServer(target, scanResult);
        }
    }

and my scanRescult class code is as below :

namespace ABX.Common.Model
{
    public class ScanResult
    {
        public ScanResult()
        {
            At = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            Interval = 1;
        }

        public string Name { get; set; }
        public long At { get; set; }
        public long Interval { get; set; }
        public JObject Values { get; set; }
        public string FileName { get; set; }

        public JObject ToJson()
        {
            JObject json = new JObject
            {
                { "at", At },
                { "i", Interval },
                { "s", Values }
            };
            return json;
        }

Solution

  • Either rename your class properties to match your JSON, rename your JSON to match your class properties, or implement a custom JsonConverter, where you can implement arbitrary mapping.