C# JSON 常用方法 - Json字符串转对象

  1. 创建项目:ConsoleApplication_Json
  2. 选择项目右键管理NuGet程序包
  3. 搜索Newtonsoft.Json 并下载安装
  4. 选择项目添加 JsonHelper.cs
  5. 添加引用:
using Newtonsoft.Json;
  1. .编写Json处理方法代码,如下:
using System;
using Newtonsoft.Json;

namespace ConsoleApplication_Json
{
    public class JsonHelper
    {
        public static decimal ToDecimal(object obj, decimal defaultValue = 0)
        {
            string s = obj == null ? "" : obj.ToString();
            decimal result;
            if (!decimal.TryParse(s, out result))
            {
                result = defaultValue;
            }
            return result;
        }

        public static string Obj2Json(object value)
        {
            return JsonConvert.SerializeObject(value);
        }

        /// <summary>
        /// 将JSON 字符串转换成对应的类型
        /// </summary>
        /// <typeparam name="T">转换后的类型</typeparam>
        /// <param name="s">需转换的字符串</param>
        /// <returns></returns>

        public static T Json2Obj<T>(string s)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(s);
            }
            catch (Exception ex)
            {
                return default(T);
            }

        }
    }
}

  1. .自定义Json格式模拟数据
{
	"id": "ko09895dd6g565d5222242125",
	"status": true,
	"httpstatus": 200,
	"data": [{
		"room": {
			"field1": "955gg2015",
			"field2": "G1020",
			"field3": "VIP",
			"field4": "大包",
			"field5": "李春凤",
			"field6": "10086611"
		},
		"address": "这里是个地址信息",
		"sign": "预订"
	}, {
		"room": {
			"field1": "955gg2016",
			"field2": "G1022",
			"field3": "VIP_null",
			"field4": "中等包",
			"field5": "李春凤",
			"field6": "10086622"
		},
		"address": "这里是个地址信洗第二个",
		"sign": "预订"
	}],
	"nextLink": "www.baidu.com"
}
  1. .格式化Json字符串用于测试
{\"id\": \"ko09895dd6g565d5222242125\", 	\"status\": true, 	\"httpstatus\": 200, 	\"data\": [{ 		\"room\": { 			\"field1\": \"955gg2015\", 			\"field2\": \"G1020\", 			\"field3\": \"VIP\", 			\"field4\": \"大包\", 			\"field5\": \"李春凤\", 			\"field6\": \"10086611\" 		}, 		\"address\": \"这里是个地址信息\", 		\"sign\": \"预订\" 	}, { 		\"room\": { 			\"field1\": \"955gg2016\", 			\"field2\": \"G1022\", 			\"field3\": \"VIP_null\", 			\"field4\": \"中等包\", 			\"field5\": \"李春凤\", 			\"field6\": \"10086622\" 		}, 		\"address\": \"这里是个地址信洗第二个\", 		\"sign\": \"预订\" 	}], 	\"nextLink\": \"www.baidu.com\" }
  1. .新建刚才与Json格式对应的类:RoomResponse.cs,代码如下
using System.Collections.Generic;

namespace ConsoleApplication_Json
{
    public class RoomResponse
    {
        public string id { get; set; }
        public string status { get; set; }
        public string httpstatus { get; set; }
        public List<Data> data { get; set; }
        public string nextLink { get; set; }
    }    
    public class Data
    {
        public Room room { get; set; }
        public string address { get; set; }
        public string sign { get; set; }
    }
    public class Room
    {
        public string field1 { get; set; }
        public string field2 { get; set; }
        public string field3 { get; set; }
        public string field4 { get; set; }
        public string field5 { get; set; }
        public string field6 { get; set; }
    }   
   
}

  1. .进入Program.cs 文件,编辑代码如下:
namespace ConsoleApplication_Json
{
    class Program
    {
        static void Main(string[] args)
        {
            var strJson = "{\"id\":\"ko09895dd6g565d5222242125\",\"status\":true,\"httpstatus\":200,\"data\":[{\"room\":{\"field1\":\"955gg2015\",\"field2\":\"G1020\",\"field3\":\"VIP\",\"field4\":\"大包\",\"field5\":\"李春凤\",\"field6\":\"10086611\"},\"address\":\"这里是个地址信息\",\"sign\":\"预订\"},{\"room\":{\"field1\":\"955gg2016\",\"field2\":\"G1022\",\"field3\":\"VIP_null\",\"field4\":\"中等包\",\"field5\":\"李春凤\",\"field6\":\"10086622\"},\"address\":\"这里是个地址信洗第二个\",\"sign\":\"预订\"}],\"nextLink\":\"www.baidu.com\"}";
            var test1 = JsonHelper.Json2Obj<RoomResponse>(strJson);
        }
    }
}

  1. .加断点,调试文件。
  2. .数据成功转换成类型对象。
  3. 补充:
        /// <summary>
        /// 使用JObjectParse
        /// 获取Json字符串中的某个值
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static JObject JObjectParse(string s)
        {
            try
            {
                var obj = JObject.Parse(s);
                return obj;
            }
            catch (Exception)
            {
                return null;                
            }
           
        }

        /// <summary>
        /// 使用JavaScriptSerializer
        /// 获取Json字符串中的某个值
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Dictionary<string, object> JavaScriptSerializer(string s)
        {
            try
            {
                JavaScriptSerializer Jss = new JavaScriptSerializer();
                Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(s);
                return DicText;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
  1. 该方法用于获取每个节点对应的内容,可直接通过obj[“data”]取出数据。
  2. 先这样吧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值