C#  结构体和List<T>类型数据转Json数据保存和读取

 一.结构体转Json

     public struct FaceLibrary
{
public string face_name;
public byte[] face_Feature;
} //序列化结构体
facelibrary = new FaceLibrary();
facelibrary.face_name = "zhangsan";
facelibrary.face_Feature = new byte[] { 0xaa, 0x22, 0x36, 0x45, 0xff }; MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FaceLibrary));
ser.WriteObject(stream1, facelibrary);
stream1.Position = ;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of Person object: ");
Console.WriteLine(sr.ReadToEnd()); //打印结果:
JSON form of Person object: [{"face_Feature":[,,,,],"face_name":"zhangsan"} //反序列化结构体
stream1.Position = ;
FaceLibrary p2 = (FaceLibrary)ser.ReadObject(stream1);
Console.WriteLine(p2.face_name);
Console.WriteLine(p2.face_Feature);
//输出结果:
wangjin01
System.Byte[] 说明: 通过如上操作,能够将结构体的数据转为Json数据 方法二: 将List<T> 结构的数据转为Json数据 public struct FaceLibrary
{
public string face_name;
public byte[] face_Feature;
} List<FaceLibrary> listfacex = new List<FaceLibrary>(); //序列化List<T>
facelibrary = new FaceLibrary();
facelibrary.face_name = "zhangsan01";
facelibrary.face_Feature = new byte[] { 0xaa, 0x22, 0x36, 0x45, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan02";
facelibrary.face_Feature = new byte[] { 0xaa, 0x22, 0x36, 0x45, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan03";
facelibrary.face_Feature = new byte[] { 0xaa, 0x22, 0x36, 0x45, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan04";
facelibrary.face_Feature = new byte[] { 0xaa, 0x22, 0x36, 0x45, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan05";
facelibrary.face_Feature = new byte[] { 0xaa, 0x22, 0x36, 0x45, 0xff };
listfacex.Add(facelibrary); MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<FaceLibrary>));
ser.WriteObject(stream1, listfacex);
stream1.Position = ;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of Person object: ");
Console.WriteLine(sr.ReadToEnd()); //输出结果:
JSON form of Person object: [
{"face_Feature":[,,,,],"face_name":"zhangsan01"},
{"face_Feature":[,,,,],"face_name":"zhangsan02"},
{"face_Feature":[,,,,],"face_name":"zhangsan03"},
{"face_Feature":[,,,,],"face_name":"zhangsan04"},
{"face_Feature":[,,,,],"face_name":"zhangsan05"}
] //反序列化List<T>
stream1.Position = ;
List<FaceLibrary> p2 = (List<FaceLibrary>)ser.ReadObject(stream1);
Console.WriteLine(p2[].face_name);
Console.WriteLine(p2[].face_Feature);
//输出结果:
zhangsan01
System.Byte[] 三.测试应用
/*
应用需求:
1. 通过List<T>将结构体类型<T>的多个数据加载到List<T>中;
2. 将List<T>数据转为Json数据,并写入到文件中;
3. 从文件中读取保存的Json数据,并还原成List<T>数据供后续调用; //说明: JavaScriptSerializer 需要导入相应的库,
命名空间: System.Web.Script.Serialization
程序集: System.Web.Extensions(位于 System.Web.Extensions.dll)
参考文件:https://msdn.microsoft.com/zh-cn/library/system.web.script.serialization.javascriptserializer.aspx
*/ //1.定义结构体和List<T>
public struct FaceLibrary
{
public string face_name;
public byte[] face_Feature;
}
FaceLibrary facelibrary;
List<FaceLibrary> listfacex = new List<FaceLibrary>(); //2. 添加数据到List<T>中
facelibrary.face_name = "zhangsan01";
facelibrary.face_Feature = new byte[] { 0xaa, 0x01, 0x11, 0x21, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan02";
facelibrary.face_Feature = new byte[] { 0xaa, 0x02, 0x12, 0x22, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan03";
facelibrary.face_Feature = new byte[] { 0xaa, 0x03, 0x13, 0x23, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan04";
facelibrary.face_Feature = new byte[] { 0xaa, 0x04, 0x14, 0x24, 0xff };
listfacex.Add(facelibrary); facelibrary.face_name = "zhangsan05";
facelibrary.face_Feature = new byte[] { 0xaa, 0x05, 0x15, 0x25, 0xff };
listfacex.Add(facelibrary); //3. 将List<T>数据转为Json数据
String str = JsonListToString(listfacex);
//JSON序列化,将List<T>转换为String
private String JsonListToString (List<FaceLibrary> list)
{
JavaScriptSerializer Serializerx = new JavaScriptSerializer();
string changestr = Serializerx.Serialize(list);
return changestr;
} //4. 将Json数据写入文件系统
FileWrite("test.txt",str)
//写入文件
private void FileWrite(string filepath,string writestr)
{
FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.Write(writestr);
sw.Close();
fs.Close();
} //5. 从文件中读取Json数据 string str = FileRead("test.txt");
//读取文件
private string FileRead(string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string str = sr.ReadToEnd();
sr.Close();
fs.Close();
return str;
} //6. 将Json数据转换为List<T>数据 List<FaceLibrary> listface = StringToJsonList(str);
//JSON反序列化,将List<T>转换为String
private List<FaceLibrary> StringToJsonList(string str)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
List<FaceLibrary> face = Serializer.Deserialize<List<FaceLibrary>>(str);
return face;
} //以上方法基本能够解决上述问题; 以上代码基于参考如下代码,
/*
// C#将Json字符串反序列化成List对象类集合 using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
public static List<T> JSONStringToList<T>(this string JsonStr)
{ JavaScriptSerializer Serializer = new JavaScriptSerializer(); List<T> objs = Serializer.Deserialize<List<T>>(JsonStr); return objs; } public static T Deserialize<T>(string json)
{ T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{ DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms);
} } //好了,我们来测试下
string JsonStr = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
List<Product> products = new List<Product>();
products = JSONStringToList<Product>(JsonStr);
//Response.Write(products.Count());
foreach (var item in products)
{
Response.Write(item.Name + ":" + item.Price + "<br />");
}
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
结果:
苹果:5.5
橘子:2.5
柿子:16 */

C# 结构体和List<T>类型数据转Json数据保存和读取的更多相关文章

  1. C# 调用C/C++动态链接库,结构体中的char*类型

    用C#掉用C++的dll直接import就可以之前有不同的类型对应,当要传递结构体的时候就有点麻烦了,这里有一个结构体里边有char*类型,这个类型在C#中调用没法声明,传string是不行的默认st ...

  2. 使用python将mysql数据库的数据转换为json数据

    由于产品运营部需要采用第三方个推平台,来推送消息.如果手动一个个键入字段和字段值,容易出错,且非常繁琐,需要将mysql的数据转换为json数据,直接复制即可. 本文将涉及到如何使用Python访问M ...

  3. [Go] golang结构体成员与函数类型

    package main import ( "fmt" ) //定义一个类型 type tsh struct { //定义成员,类型是func() string test func ...

  4. mybatis 处理数组类型及使用Json格式保存数据 JsonTypeHandler and ArrayTypeHandler

    mybatis 比 ibatis 改进了很多,特别是支持了注解,支持了plugin inteceptor,也给开发者带来了更多的灵活性,相比其他ORM,我还是挺喜欢mybatis的. 闲言碎语不要讲, ...

  5. .net动态类型在处理json数据方面的应用

    我们在.net中处理json数据时,经常需要定义相应的类.比如json数据:{ "name" : "hello", "age" : 18 } ...

  6. 将Dictionary序列化为json数据 、json数据反序列化为Dictionary

    需要引用System.Web.Extensions  dll类库 /// <summary> /// 将json数据反序列化为Dictionary /// </summary> ...

  7. 使用jQuery解析JSON数据(由ajax发送请求到php文件处理数据返回json数据,然后解析json写入html中呈现)

    在上一篇的Struts2之ajax初析中,我们得到了comments对象的JSON数据,在本篇中,我们将使用jQuery进行数据解析. 我们先以解析上例中的comments对象的JSON数据为例,然后 ...

  8. [Swift通天遁地]四、网络和线程-(5)解析网络请求数据:String(字符串)、Data(二进制数据)和JSON数据

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  9. Numpy中数据的常用的保存与读取方法

    小书匠 深度学习  文章目录: 1.保存为二进制文件(.npy/.npz) numpy.save numpy.savez numpy.savez_compressed 2.保存到文本文件 numpy. ...

随机推荐

  1. nginx内容

    nginx工作在7层:web server(静态内容 static contents)web reverse proxy(反向代理http,https,mail),cache(带缓存功能) proxy ...

  2. Caused by: java.lang.IllegalArgumentException: argument type mismatch

    下面是我的报错信息 at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java: ...

  3. .net core 2.2 修改IdentityUser主键标识类型

    .net core2.2,生成WebApi或者MVC项目后,Identity 1.增加ApplicationUser.cs文件,内容如下 public class ApplicationUser : ...

  4. eclipse配置maven仓库

    在eclipse中搭建maven工程时,首先需要搭建好maven本地仓库,搭建过程比较简单 1.首先,在eclipse中,打开windows->Maven->User Settings; ...

  5. 在Maven中新增自定的jar包

    引言: 在软件项目中,Maven提供了一体化的类库管理系统,非常实用.但是,如果新增的类库jar在网络上无法获取到,如何在本地按照Maven的规则添加进来呢?本文将通过一个小例子展示新增过程. 背景介 ...

  6. Container and Injection in Java

    一.Container 1.为什么使用Container 通常,瘦客户端多层应用程序很难编写,因为它们涉及处理事务和状态管理.多线程.资源池和其他复杂的低级细节的复杂代码行.基于组件和独立于平台的Ja ...

  7. jq 获取下一个兄弟原素 下拉箭头旋转

    $('.weui-cells__title').on("click", function(e,rr){ isshow=$(this).attr('isshow') if(issho ...

  8. PhoenixFD插件流体模拟——UI布局【Output】详解

    Liquid Output 流体输出  本文主要讲解Output折叠栏中的内容.原文地址:https://docs.chaosgroup.com/display/PHX3MAX/Liquid+Outp ...

  9. 音视频处理概要 markdown

    最近要想办法把录制的音视频进行拼接. 比方说此次录制的视频有三段,通过高清直播编码器录制,录制下的标准为h.264 直接用ffmpeg简单拼接,音频会丢失,所以有了此次解决方案(有可能会繁琐,简单方案 ...

  10. [Solution] 885. Spiral Matrix Ⅲ

    Difficulty: Medium Problem On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) f ...