C#将Json字符串转换为Object

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (334)

我一直试图让这个工作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:\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;
    }

现在我想尝试检查每个条目,如果数据是本周。然后从本周获取每个条目的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);

其中SleepEntry被修改为

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

扫码关注云+社区

领取腾讯云代金券