C# 将 JSON 字符串转换为对象



我一直在尝试让它工作 4 天,但我似乎无法弄清楚。我通过 api 接收一个 json 字符串,并希望将数据解析为不同的字符串和整数:

示例 JSON 字符串:

"[{"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"}]"

我试图转换为什么:

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; }
}

读取 json 的代码:

    public void Get_Monthly_Data()
    {

        StreamReader reader = new StreamReader(@"C:UsersRubensourcereposHealth App GoedeHealth App GoedeResourcesCutstomer_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;
    }

现在我想尝试检查每个条目,如果数据是本周。然后只需获取本周每个条目的Entry_value,现在将其显示在文本框中。任何帮助或提示将不胜感激。

您实际上并不需要这些支持字段。您可以使用 { get; set; } 将它们编写为自动属性。

您的JSON中有一些非常烦人的东西,即日期和数字作为字符串。因此,我建议您使用 QuickType 之类的东西来为您生成 C# 模型类。

结果如下:

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();
}

用法:

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

现在我想尝试检查每个条目,如果数据是本周。然后只需获取本周每个条目的Entry_value,现在将其显示在文本框中。

要确定两个日期时间是否在同一周,我们可以使用此方法:

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;
}

从这个问题复制而来。

然后,这可以通过一点 LINQ 来完成:

List<long> list = sleepEntries.Where(x => DatesAreInTheSameWeek(x.EntryDate.DateTime, DateTime.Now)).Select(x => x.EntryValue).ToList();

你的 Json 字符串是一个数组,所以你需要使用

var result = JsonConvert.DeserializeObject<IEnumerable<SleepEntry>>(str);

其中睡眠条目被修改为

public class SleepEntry
{
string Entry_number;
string Entry_date;
string Customer_number;
string Entry_value;
string Comment;
[JsonProperty("Entry_number")]
public string Entry_number1 { get => Entry_number; set => Entry_number = value; }
[JsonProperty("Entry_date")]
public string Entry_date1 { get => Entry_date; set => Entry_date = value; }
 [JsonProperty("Custom_number1")]
public string Customer_number1 { get => Customer_number; set => Customer_number = value; }
[JsonProperty("Entry_value")]
public string Entry_value1 { get => Entry_value; set => Entry_value = value; }
[JsonProperty("Comment")]
public string Comment1 { get => Comment; set => Comment = value; }
}

PS:您可以随时删除支持字段并使用 自动属性,除非您已将其用于目的

用于获取本周首次入场的价值。

var today = DateTime.Now;
var startOfWeek = today.AddDays((int)DateTime.Now.DayOfWeek * -1);

var value = result.Where(x=>DateTime.Parse(x.Entry_date1) > startOfWeek 
                        && DateTime.Parse(x.Entry_date1) < today.AddDays(7))
                  .Select(x=>x.Entry_value1).FirstOrDefault();

相关内容

  • 没有找到相关文章

最新更新