1

I need to deserialize my json data. I am using Newtonsoft.Json for json operations. I tried a lot of method to deserialize this data but i failed. Btw, I need to summarize my system for better understanding. I am posting data every minute to an API. And its response to me. So I am trying to deserialize the response.

What need I do to deserialize this json and use it like a normal c# object? I want to deserialize res variable. Thank you for your interest.

Here is the main code

 var data = new SendData
            {
                Readtime = time,
                Stationid = new Guid(_stationid),
                SoftwareVersion = softwareVersion,
                Period = period,
                AkisHizi = akisHizi,
                AkisHizi_Status = status,
                AKM = akm,
                AKM_Status = status,
                CozunmusOksijen = cozunmusOksijen,
                CozunmusOksijen_Status = status,
                Debi = debi,
                Debi_Status = status,
                DesarjDebi = desarjDebi,
                DesarjDebi_Status = status,
                KOi = koi,
                KOi_Status = status,
                pH = ph,
                pH_Status = status,
                Sicaklik = sicaklik,
                Sicaklik_Status = status,
                Iletkenlik = iletkenlik,
                Iletkenlik_Status = status
            };

            var res = Services.sendData(data);

            MessageBox.Show(res.objects.ToString());

Here is the services model PostData method

 private ResultStatus<T> PostData<T>(string url, string data) where T : new()
        {
            try
            {
                using (var webClient = new WebClient())
                {

                    webClient.Encoding = Encoding.UTF8;
                    webClient.Headers.Add("AToken", JsonConvert.SerializeObject(new AToken { TicketId = this.TicketId.ToString() }));

                    var resp = webClient.UploadString(this.Url + url, data);

                    return JsonConvert.DeserializeObject<ResultStatus<T>>(resp);

                }
            }
            catch (Exception ex)
            {
                return new ResultStatus<T>
                {
                    message = ex.Message + System.Environment.NewLine + url
                };
            }

        }

Here is the sendData method

public ResultStatus<object> sendData(SendData data)
        {

            var res = PostData<object>(this.stationType.ToString() + "/SendData", JsonConvert.SerializeObject(data));

            return res;

        }

Here is the MessageBox result (json data)

{ 
'Period': 1, 
'ReadTime': 
'2022-08-22714:01:00', 
'AKM': 65.73, 
'AKM_Status': 1,
'CozunmusOksijen': 0.2,
'CozunmusOksijen_Status': 1,
'Debi': 1.0,
'Debi_Status': 1,
'KOi': 25.1,
'KOi_Status': 1
}
7
  • Why are you using WebClient at all? That's an obsolete class replaced by HttpClient 10 years ago. And that's not an exaggeration - HttpClient was introduced in 2012. All supported .NET versions have it. JSON.NET works anyway, so it's unclear what the problem is here. Commented Aug 22, 2022 at 11:21
  • Thanks for your comment but this is not the correct answer. Commented Aug 22, 2022 at 11:25
  • You can reduce all of this code to just var response= await httpClient.PostAsJsonAsync(url,data); and then read the payload with var newdata=await response.Content.ReadFromJsonAsync<MyPayload>();. This won't help if the JSON response or URL is wrong though. Commented Aug 22, 2022 at 11:26
  • this is not the correct answer. this is not a correct question. You're asking people to help with a problem but never actually describe any problem. Did you get an exception? What does it actually say? It's not even clear whether JSON.NET is involved at all. Are you calling the wrong URL? Is the HTTP response different than your object? Commented Aug 22, 2022 at 11:28
  • Unless stationType is a string starting with a slash, or this.Url ends with a slash, this.Url + url will result in a bad URL. That's just one of the problems in the question's code that could cause it to fail. If you used the Uri class instead you'd get an error when combining the URL parts, not when making the actual call. Commented Aug 22, 2022 at 11:30

1 Answer 1

1

Your JSON is probably,

{ 
"Period": 1, 
"ReadTime": "2022-08-22T14:01:00", 
"AKM": 65.73, 
"AKM_Status": 1,
"CozunmusOksijen": 0.2,
"CozunmusOksijen_Status": 1,
"Debi2": 1.0,
"Debi_Status": 1,
"KOi": 25.1,
"KOi_Status": 1
}

From https://app.quicktype.io/, a C# model would be,

// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using QuickType;
//
//    var thing = Thing.FromJson(jsonString);

namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Thing
    {
        [JsonProperty("Period")]
        public long Period { get; set; }

        [JsonProperty("ReadTime")]
        public DateTimeOffset ReadTime { get; set; }

        [JsonProperty("AKM")]
        public double Akm { get; set; }

        [JsonProperty("AKM_Status")]
        public long AkmStatus { get; set; }

        [JsonProperty("CozunmusOksijen")]
        public double CozunmusOksijen { get; set; }

        [JsonProperty("CozunmusOksijen_Status")]
        public long CozunmusOksijenStatus { get; set; }

        [JsonProperty("Debi2")]
        public long Debi2 { get; set; }

        [JsonProperty("Debi_Status")]
        public long DebiStatus { get; set; }

        [JsonProperty("KOi")]
        public double KOi { get; set; }

        [JsonProperty("KOi_Status")]
        public long KOiStatus { get; set; }
    }

    public partial class Thing
    {
        public static Thing FromJson(string json) => JsonConvert.DeserializeObject<Thing>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Thing self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

As per https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0#how-to-read-json-as-net-objects-deserialize

 Thing? thing = JsonSerializer.Deserialize<Thing>(res);
Sign up to request clarification or add additional context in comments.

3 Comments

Let me try it, thanks for your help and interest.
I tried it but, when i write res in ( ) it says i know its funny but 1503: object to newtonsoft.json.reader how can we solve it? thanks for your interest again
Thing? thing = JsonSerializer.Deserialize<Thing>(res); this code still returns 1503: object to newtonsoft.json.reader sorry about that..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.