Json.NET

鉴于最近记性总是不好,所以,将所研究过的技术做成CSDN写在博客上,本文主要叙述。newtonsoft的nuget包,需求是通信内容控制位Json.不得不拾起。其实我以前做过类似项目,忘干净了。又继续干。

首先新建一个类对象。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace lua_core_windows
{
 public  class ConfigureMessage
  {
    [JsonProperty("File_Name")]
    public string File_Name { get; set; }
    [JsonProperty("Call_Style")]
    public int Call_Style { get; set; }
    [JsonProperty("FunctionOrNot")]
    public string FunctionOrNot { get; set; }
    [JsonProperty("Timer_")]
    public string Timer_ { get; set; }
    [JsonProperty("Timing_Time")]
    public string Timing_Time { get; set; }
    public static string getJson(ConfigureMessage cm)
    {
      string json = JsonConvert.SerializeObject(cm, Formatting.Indented);
      return json;
    }
    public static ConfigureMessage set(string json)
    {
      ConfigureMessage cm = new ConfigureMessage();
      cm = JsonConvert.DeserializeObject<ConfigureMessage>(json);
      return cm;
    }
  }
}

个人习惯,习惯构造类的时候同时给定get,put方法。

调用方法

  string json = @"{
'call_style':'11111',
'file_Name':'',
'Timer_':'',
'functionOrNot':'',
'timing_Time':''
}";


      ConfigureMessage cm = new ConfigureMessage();
      cm.call_Style = 0;
      cm.file_Name = "";
      cm.timing_Time ="";

      ConfigureMessage.getJson(cm);

      ConfigureMessage cm1 = ConfigureMessage.set(json);

记录newtonsoft包使用方式。其实还有object之类的。

鉴于情景的使用增加,继续添加文章篇幅,有如下Json文件

[
    {
        "Call_Style": "11111",
        "File_Name": "",
        "Timer_": "",
        "FunctionOrNot": "",
        "Timing_Time": ""
    },
    {
        "Call_style": "3",
        "File_Name": "",
        "Timer_": "",
        "FunctionOrNot": "",
        "Timing_Time": ""
    }
]

使用其代码为

string path = ".//Json.json";
      StreamReader sr = new StreamReader(path, Encoding.Default);
      String line;
      string jsonobj = "";
      while ((line = sr.ReadLine()) != null)
      {
        jsonobj = jsonobj + line.ToString();
      }
      sr.Close();
      var arrdata = Newtonsoft.Json.Linq.JArray.Parse(jsonobj);

      List<ConfigureMessage> obj2 = arrdata.ToObject<List<ConfigureMessage>>();

意图很明显直接读取json解析内容,即解决传递问题,也解决配置问题。然后开始新的设计。至于如何序列化jobject jarray jpropreat具体的可以看到newtonsoft.json官网。

https://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值