Newtonsoft.Json 常規用法


安裝 Newtonsoft.Json

Install-Package Newtonsoft.Json

常用using

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

序列化

//序列化  對象 -> JSON 字符串
string json = JsonConvert.SerializeObject(object);

//分序列化 JSON 字符串 -> 對象
var jsonObj = JsonConvert.DeserializeObject<object>(json);
int[] arr = JsonConvert.DeserializeObject("[1,2,3]", typeof(int[])) as int[];

通過對象直接獲取字符串:復制對象,然后打開LINQPad 開,然后試用快捷鍵 Shfit+Alt+V 即可獲取字符串。

--對象
{"code":0,"msg":"success","data":{"total":3,"details":{"codes":["1","2","3"]}}}
--字符串
"{\"code\":0,\"msg\":\"success\",\"data\":{\"total\":3,\"details\":{\"codes\":[\"1\",\"2\",\"3\"]}}}"

特性

[JsonProperty("student")]//重命名屬性名
[JsonProperty(PropertyName = "student")]
[JsonIgnore]//序列化時忽略此字段
[DisplayName("學生")]
public string Student { get; set; }

配置

局部配置

JsonSerializerSettings jsonSerializerSettings= new JsonSerializerSettings();
jsonSerializerSettings.Formatting= Formatting.Indented;
var json = JsonConvert.SerializeObject(reportModel, jsonSerializerSettings);

全局配置

NuGet安裝 Microsoft.AspNetCore.Mvc.NewtonsoftJson

程序全局配置

JsonSerializerSettings setting = new JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
    setting.Formatting = Formatting.Indented;
    return setting;
});

API返回結果配置

builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    //修改屬性名稱的序列化方式,首字母小寫,即駝峰樣式
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    //修改屬性名稱的序列化方式,蛇形命名,大寫字母變小寫+下划線。 比如:ProductName => product_name
    options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() };

    //字符串格式化
    options.SerializerSettings.Formatting = Formatting.Indented;

    //日期類型默認格式化處理 方式1
    options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy/MM/dd HH:mm:ss" });
    //日期類型默認格式化處理 方式2
    options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
    options.SerializerSettings.DateFormatString = "yyyy/MM/dd HH:mm:ss";

    //忽略循環引用
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

    //解決命名不一致問題 
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();

    //忽略空值字段
    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

    //忽略默認值
    options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;

    //包含默認值
    options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;

    //多態反序列化
    options.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
});

常規用法

類型轉換

常用類型

  • BinaryConverter
  • BsonObjectIdConverter
  • CustomCreationConverter
  • DataSetConverter
  • DataTableConverter
  • DateTimeConverterBase
  • DiscriminatedUnionConverter
  • EntityKeyMemberConverter
  • ExpandoObjectConverter
  • IsoDateTimeConverter
  • JavaScriptDateTimeConverter
  • KeyValuePairConverter
  • RegexConverter
  • StringEnumConverter
  • UnixDateTimeConverter
  • VersionConverter
  • XmlNodeConverter

使用方式

  • 字段添加: [JsonConverter(typeof(DataTableConverter))]
  • 配置添加:JsonConvert.SerializeObject(dt, new DataTableConverter(), new DataSetConverter());

字段全部小寫

var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);


public class LowercaseContractResolver : DefaultContractResolver
{
    protected override string ResolvePropertyName(string propertyName)
    {
        return propertyName.ToLower();
    }
}

Double/Decimal移除小數點

DoubleDecimal類型數據在序列化時會默認添加一個小數點並隨0.比如1賦值1.0
解決方案是自定義添加類型轉換


/// <summary>
/// decimal格式化
/// </summary>
public class JsonConverterDecimal : JsonConverter
{
    //是否可以轉換
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(decimal) || objectType == typeof(decimal?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.ValueType == null && reader.Value == null) return null;
        decimal.TryParse(reader.Value != null ? reader.Value.ToString() : "", out decimal value);
        return value.ToString("F2");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value == null ? value : value.ToString());
    }
}


/// <summary>
/// double格式化
/// </summary>
public class JsonConverterDouble : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(double) || objectType == typeof(double?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.ValueType == null && reader.Value == null) return null;
        double.TryParse(reader.Value != null ? reader.Value.ToString() : "", out double value);
        return value.ToString("F2");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value == null ? value : value.ToString());
    }
}

在配置中添加

JsonSerializerSettings jsonSerializerSettings= new JsonSerializerSettings();
jsonSerializerSettings.Converters = new List<JsonConverter> { new JsonConverterDecimal(), new JsonConverterDouble() };
var json = JsonConvert.SerializeObject(reportModel, jsonSerializerSettings);

或者在字段中添加配置

[JsonConverter(typeof(JsonConverterDecimal))]
public decimal TotalNum { get; set; }

反向剔除

默認都不顯示,手工指定要顯示的,使用 MemberSerialization.OptIn 配合 JsonProperty
以下代碼只會序列化ProductName ,其他字段都會忽略

[JsonObject(MemberSerialization.OptIn)]
public class ReportModel
{
    [JsonProperty] 
    public string ProductName { get; set; }
    public int ProductId1 { get; set; }
    public int ProductId2 { get; set; }
    public int ProductId3 { get; set; }
}

枚舉返回字符串

默認情況下對於實體里面的枚舉類型系統是格式化成改枚舉對應的整型數值。在字段屬性上加上JsonConverter(typeof(StringEnumConverter))會將枚舉值轉換成對應的字符串

public class TestEnmu
{
    [JsonConverter(typeof(StringEnumConverter))]
    public NotifyType Type { get; set; }
}
public enum NotifyType
{
    Mail = 0,
    SMS = 1
}

多個json合並到一個Model


var reportModel = new ReportModel();
var json1 = "{'ProductName':'法式小眾設計感長裙氣質顯瘦純白色仙女連衣裙'}";
var json2 = "{'TotalCustomerCount':1000,'TotalPayment':100.0,'TotalProductCount':10000}";

JsonConvert.PopulateObject(json1, reportModel);
JsonConvert.PopulateObject(json2, reportModel);


public class ReportModel
{
    public string ProductName { get; set; }
    public int TotalCustomerCount { get; set; }
    public decimal TotalPayment { get; set; }
    public int TotalProductCount { get; set; }
}

驗證JSON字符串

public static bool ValidateJSON(this string s)
{
    try
    {
        Newtonsoft.Json.Linq.JToken.Parse(s);
        return true;
    }
    catch
    {
        return false;
    }
}

JObject、JArray、JProperty、JValue 的使用

  • JObject用來生成一個JSON對象{}
  • JArray用來生成一個JSON數組[]
  • JProperty用來生成一個JSON數據key:value
  • JValue則直接生成一個JSON值

創建json對象

把JObject理解為C#中的一個類,那么JProperty就是它的屬性

案例1

var jObject = new
{
    msg = "success",
    data = new
    {
        total = 1,
        diff = new int[3] { 1, 2, 3 }
    }
};
Console.WriteLine(JsonConvert.SerializeObject(jObject));

輸出:
/*
{
    "msg": "success",
    "data": {
        "total": 1,
        "diff": [1, 2, 3]
    }
}
*/

案例2

var jobject = new JObject();
jobject.Add(new JProperty("name", "jack"));
jobject.Add(new JProperty("age", "28"));
jobject.Add(new JProperty("content", new JObject(new JProperty("hobby", "game"))));
Console.WriteLine(jobject);

輸出:
/*
{
  "name": "jack",
  "age": "28",
  "content": {
    "hobby": "game"
  }
}
*/

案例3

var jobject = new JObject { new JProperty("name", "renee"), new JProperty("age", 30) };

輸出:
/*
{
  "name": "renee",
  "age": 30
}
*/

案例4

JArray array = new JArray();
array.Add("GongHui Linq");
array.Add(new DateTime(2015, 12, 14));
var jobject = new JObject();
jobject.Add(new JProperty("name", "jack"));
jobject.Add(new JProperty("age", "28"));
jobject.Add(new JProperty("content", new JObject(new JProperty("hobby", "game"))));
jobject["myArray"] = array;
var jarray = new JArray();
jarray.Add(jobject);
jarray.Add(new JObject(new JProperty("name", "renne")));
Console.WriteLine(jarray);

輸出
/*
 [
  {
    "name": "jack",
    "age": "28",
    "content": {
      "hobby": "game"
    },
    "myArray": [
      "GongHui Linq",
      "2015-12-14T00:00:00"
    ]
  },
  {
    "name": "renne"
  }
]
 */

解析json對象

var json = "{\"msg\":\"success\",\"code\":200,\"data\":\"data\"}";

var jobject = JObject.Parse(json);

//獲取msg對象的值
Console.WriteLine(jobject.Value<string>("msg"));
Console.WriteLine(jobject["msg"]);

//獲取code對象的值
Console.WriteLine(jobject.GetValue("code"));

//判斷對象是否存在
if (jobject.ContainsKey("code") && jobject.Value<string>("code").Equals("200"))
    Console.WriteLine("true");
else
    Console.WriteLine("false");


輸出
/*
success
success
200
True
 */

案例2

//創建一個對象
var Object = new
{
    code = 0,
    msg = "success",
    data = new
    {
        total = 3,
        details = new { codes = new string[] { "1", "2", "3" } }
    }
};
//對象轉字符串
var json = JsonConvert.SerializeObject(Object);
//輸出json
Console.WriteLine(json);
//解析對象
var jObject = JObject.Parse(json);
var jArray = JArray.Parse(jObject["data"]["details"]["codes"].ToString());
//JArray轉換對象
var list = jArray.ToObject<string[]>();
foreach (var item in list)
    Console.WriteLine(item);


輸出
/*
{
    "code": 0,
    "msg": "success",
    "data": {
        "total": 3,
        "details": {
            "codes": ["1", "2", "3"]
        }
    }
}
1
2
3
 */

案例3

var json = @"{
                           'DisplayName': '新一代算法模型',
                           'CustomerType': 1,
                           'Report': {
                             'TotalCustomerCount': 1000,
                             'TotalTradeCount': 50
                           },
                           'CustomerIDHash': [1,2,3,4,5]
                         }";

var dict = JsonConvert.DeserializeObject<Dictionary<object, object>>(json);
var report = dict["Report"] as JObject;
var totalCustomerCount = report["TotalCustomerCount"];

Console.WriteLine($"totalCustomerCount={totalCustomerCount}");

var arr = dict["CustomerIDHash"] as JArray;
var list = arr.Select(m => m.Value<int>()).ToList();

Console.WriteLine($"list={string.Join(",", list)}");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM