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

时间:2019-01-13 08:00:01

标签: c# json object json.net

我已经尝试使它工作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即可,现在将其显示在文本框中。任何帮助或提示将不胜感激。

2 个答案:

答案 0 :(得分:1)

您的Json字符串是一个数组,因此您需要使用

interface searchParam {
  key: string;
  values: string[];
}

const values: searchParam = [
  {key:'1', values: ['1','2','3']},
  {key:'2', values: ['1','2','3']},
  {key:'3', values: ['1','5','6']},
  {key:'3', values: ['1','2','3']},
  {key:'5', values: ['1','2','3']},
  {key:'6', values: ['1','2','3']},
];

const args: searchParam = [
    {key:'1', values: ['1','2','3']},
    {key:'3', values: ['1','5','6']},
];

function transform(val:searchParam[],args:searchParam[]){
  const result = [];
  for(let arg of args){
     const filtered = val.filter((e)=>{
       return e.key === arg.key &&
       e.values.every((ele,index)=>e.values[index] === arg.values[index]);
      });
     result.push(...filtered);
  }
  return result;
}

console.log(transform(values,args));

将SleepEntry修改为

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

PS:您始终可以删除后备字段并使用“自动属性”,除非您已将其用于目的

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

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

答案 1 :(得分:1)

您实际上不需要那些后备字段。您可以使用{ 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;
}

从此question复制。

然后可以使用一些LINQ来完成:

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