Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert Json string into Object

I have been trying to get this working for 4 days now but I just cant seem to figure it out. Im receiving a json string through an api and want to parse the data into different strings and ints:

Example Json String:

"[{\"Entry_number\":\"4\",\"Entry_date\":\"2019-01-10 18:22:55\",\"Customer_number\":\"16\",\"Entry_value\":\"13\",\"Comment\":\"Nu gaat ie t GVD doen\"},
    {\"Entry_number\":\"5\",\"Entry_date\":\"2019-01-12 14:34:23\",\"Customer_number\":\"16\",\"Entry_value\":\"10\",\"Comment\":\"TextBox\"},
    {\"Entry_number\":\"6\",\"Entry_date\":\"2019-01-12 14:34:31\",\"Customer_number\":\"16\",\"Entry_value\":\"10\",\"Comment\":\"Onrustig\"},
    {\"Entry_number\":\"7\",\"Entry_date\":\"2019-01-12 14:34:37\",\"Customer_number\":\"16\",\"Entry_value\":\"10\",\"Comment\":\"Ziek\"}]"

What im trying to convert to:

public class SleepEntry
{
    string Entry_number;
    string Entry_date;
    string Customer_number;
    string Entry_value;
    string Comment;

    public string Entry_number1 { get => Entry_number; set => Entry_number = value; }

    public string Entry_date1 { get => Entry_date; set => Entry_date = value; }

    public string Customer_number1 { get => Customer_number; set => Customer_number = value; }

    public string Entry_value1 { get => Entry_value; set => Entry_value = value; }

    public string Comment1 { get => Comment; set => Comment = value; }
}

public class SleepData
{
    private List<SleepEntry> plants; 

    public List<SleepEntry> Plants { get => plants; set => plants = value; }
}

Code that reads the json:

    public void Get_Monthly_Data()
    {


        StreamReader reader = new StreamReader(@"C:\Users\Ruben\source\repos\Health App Goede\Health App Goede\Resources\Cutstomer_ID.txt");
        Customernumber = reader.ReadLine();
        reader.Close();
        //string json = entrys();

        //convert json to series objects
        SleepData sleepdata = JsonConvert.DeserializeObject<SleepData>(entrys());

    }

    public string entrys()
    {
        string json = get.get_customer_monitoring_entry("sleep", Customernumber);

        return json;
    }

Now I want to try and Check for each entry if the dat was this week. Then just get the Entry_value of eacht entry from this week and for now show it in a textbox. Any help or tips would be really appreciated.

like image 425
im_ Ruben Avatar asked Apr 18 '26 15:04

im_ Ruben


1 Answers

You don't actually need those backing fields. You can just write them as automatic properties with { get; set; }.

Your JSON has some quite annoying things in it, namely dates and numbers as strings. Therefore, I recommend you to use something like QuickType to have the C# model class generated for you.

Here is the result:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public partial class SleepEntry
{
    [JsonProperty("Entry_number")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long EntryNumber { get; set; }

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

    [JsonProperty("Customer_number")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long CustomerNumber { get; set; }

    [JsonProperty("Entry_value")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long EntryValue { get; set; }

    [JsonProperty("Comment")]
    public string Comment { get; set; }
}

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

public static class Serialize
{
    public static string ToJson(this SleepEntry[] 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 }
        },
    };
}

internal class ParseStringConverter : JsonConverter
{
    public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

    public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        var value = serializer.Deserialize<string>(reader);
        long l;
        if (Int64.TryParse(value, out l))
        {
            return l;
        }
        throw new Exception("Cannot unmarshal type long");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        if (untypedValue == null)
        {
            serializer.Serialize(writer, null);
            return;
        }
        var value = (long)untypedValue;
        serializer.Serialize(writer, value.ToString());
        return;
    }

    public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}

Usage:

// sleepEntries is a SleepEntry[]
var sleepEntries = SleepEntry.FromJson(jsonString);

Now I want to try and Check for each entry if the dat was this week. Then just get the Entry_value of eacht entry from this week and for now show it in a textbox.

To figure out if two date times are in the same week, we can use this method:

private bool DatesAreInTheSameWeek(DateTime date1, DateTime date2)
{
    var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
    var d1 = date1.Date.AddDays(-1 * (int)cal.GetDayOfWeek(date1));
    var d2 = date2.Date.AddDays(-1 * (int)cal.GetDayOfWeek(date2));

    return d1 == d2;
}

copied from this question.

Then this can be done with a little bit of LINQ:

List<long> list = sleepEntries.Where(x => DatesAreInTheSameWeek(x.EntryDate.DateTime, DateTime.Now)).Select(x => x.EntryValue).ToList();
like image 176
Sweeper Avatar answered Apr 21 '26 06:04

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!