c#如何序列化与反序列化json文件
见网站: http://www.json.org/
代码如下:
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text; namespace MiniJSON
{
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// } /// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json
{
#region Parser sealed class Parser : IDisposable
{
const string WORD_BREAK = "{}[],:\""; public static bool IsWordBreak(char c)
{
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -;
} public static object Parse(string jsonString)
{
using (var instance = new Parser(jsonString))
return instance.ParseValue();
} enum TOKEN
{
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
}; StringReader m_json; Parser(string jsonString)
{
m_json = new StringReader(jsonString);
} public void Dispose()
{
m_json.Dispose();
m_json = null;
} object ParseValue()
{
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
} object ParseByToken(TOKEN token)
{
switch (token)
{
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
} Dictionary<string, object> ParseObject()
{
var table = new Dictionary<string, object>(); // ditch opening brace
m_json.Read(); // {
while (true)
{
switch (NextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null)
return null; // :
if (NextToken != TOKEN.COLON)
return null;
// ditch the colon
m_json.Read(); // value
table[name] = ParseValue();
break;
}
}
} List<object> ParseArray()
{
var array = new List<object>(); // ditch opening bracket
m_json.Read(); // [
var parsing = true;
while (parsing)
{
TOKEN nextToken = NextToken; switch (nextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken); array.Add(value);
break;
}
} return array;
} string ParseString()
{
var sb = new StringBuilder();
char c; // ditch opening quote
m_json.Read(); bool parsing = true;
while (parsing)
{
if (m_json.Peek() == -)
{
parsing = false;
break;
} c = NextChar;
switch (c)
{
case '"':
parsing = false;
break;
case '\\':
if (m_json.Peek() == -)
{
parsing = false;
break;
} c = NextChar;
switch (c)
{
case '"':
case '\\':
case '/':
sb.Append(c);
break;
case 'b':
sb.Append('\b');
break;
case 'f':
sb.Append('\f');
break;
case 'n':
sb.Append('\n');
break;
case 'r':
sb.Append('\r');
break;
case 't':
sb.Append('\t');
break;
case 'u':
var hex = new char[]; for (int i = ; i < ; i++)
{
hex[i] = NextChar;
} sb.Append((char)Convert.ToInt32(new string(hex), ));
break;
}
break;
default:
sb.Append(c);
break;
}
} return sb.ToString();
} object ParseNumber()
{
string number = NextWord; if (number.IndexOf('.') == -)
{
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
} double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
} void EatWhitespace()
{
while (Char.IsWhiteSpace(PeekChar))
{
m_json.Read(); if (m_json.Peek() == -)
break;
}
} #region Properties char PeekChar
{
get { return Convert.ToChar(m_json.Peek()); }
} char NextChar
{
get { return Convert.ToChar(m_json.Read()); }
} string NextWord
{
get
{
var word = new StringBuilder(); while (!IsWordBreak(PeekChar))
{
word.Append(NextChar); if (m_json.Peek() == -)
break;
} return word.ToString();
}
} TOKEN NextToken
{
get
{
EatWhitespace(); if (m_json.Peek() == -)
return TOKEN.NONE; switch (PeekChar)
{
case '{':
return TOKEN.CURLY_OPEN;
case '}':
m_json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
m_json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
m_json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '-':
return TOKEN.NUMBER;
} switch (NextWord)
{
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
} return TOKEN.NONE;
}
} #endregion
} #endregion #region Serializer sealed class Serializer
{
StringBuilder m_builder; Serializer()
{
m_builder = new StringBuilder();
} public static string Serialize(object obj)
{
var instance = new Serializer(); instance.SerializeValue(obj); return instance.m_builder.ToString();
} void SerializeValue(object value)
{
IList asList;
IDictionary asDict;
string asStr; if (value == null)
m_builder.Append("null");
else if ((asStr = value as string) != null)
SerializeString(asStr);
else if (value is bool)
m_builder.Append((bool)value ? "true" : "false");
else if ((asList = value as IList) != null)
SerializeArray(asList);
else if ((asDict = value as IDictionary) != null)
SerializeObject(asDict);
else if (value is char)
SerializeString(new string((char)value, ));
else
SerializeOther(value);
} void SerializeObject(IDictionary obj)
{
bool first = true; m_builder.Append('{'); foreach (object e in obj.Keys)
{
if (!first)
m_builder.Append(','); SerializeString(e.ToString());
m_builder.Append(':'); SerializeValue(obj[e]); first = false;
} m_builder.Append('}');
} void SerializeArray(IList anArray)
{
m_builder.Append('['); bool first = true; foreach (object obj in anArray)
{
if (!first)
m_builder.Append(','); SerializeValue(obj); first = false;
} m_builder.Append(']');
} void SerializeString(string str)
{
m_builder.Append('\"'); char[] charArray = str.ToCharArray();
foreach (var c in charArray)
{
switch (c)
{
case '"':
m_builder.Append("\\\"");
break;
case '\\':
m_builder.Append("\\\\");
break;
case '\b':
m_builder.Append("\\b");
break;
case '\f':
m_builder.Append("\\f");
break;
case '\n':
m_builder.Append("\\n");
break;
case '\r':
m_builder.Append("\\r");
break;
case '\t':
m_builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= ) && (codepoint <= ))
m_builder.Append(c);
else
{
m_builder.Append("\\u");
m_builder.Append(codepoint.ToString("x4"));
}
break;
}
} m_builder.Append('\"');
} void SerializeOther(object value)
{
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float)
{
m_builder.Append(((float)value).ToString("R"));
}
else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong)
{
m_builder.Append(value);
}
else if (value is double
|| value is decimal)
{
m_builder.Append(Convert.ToDouble(value).ToString("R"));
}
else
{
SerializeString(value.ToString());
}
}
} #endregion /// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json)
{
// save the string for debug information
if (json == null)
return null; return Parser.Parse(json);
} /// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj)
{
return Serializer.Serialize(obj);
}
}
}
MiniJson
转载请注明出处:http://www.cnblogs.com/jietian331/p/5779996.html
c#如何序列化与反序列化json文件的更多相关文章
- C#序列化及反序列化Json对象通用类JsonHelper
当今的程序界Json大行其道.因为Json对象具有简短高效等优势,广受广大C#码农喜爱.这里发一个序列化及反序列化Json对象通用类库,希望对大家有用. public class JsonHelper ...
- Jackson序列化和反序列化Json数据完整示例
Jackson序列化和反序列化Json数据 Web技术发展的今天,Json和XML已经成为了web数据的事实标准,然而这种格式化的数据手工解析又非常麻烦,软件工程界永远不缺少工具,每当有需求的时候就会 ...
- (推荐JsonConvert )序列化和反序列化Json
在Json文本和.Net对象之间转换最快的方法是试用JsonSerializer. JsonSerializer通过将.Net对象属性名称映射到Json属性名称,并为其复制值,将.Net对象转换为其J ...
- c# 类实例序列化反序列化json文件 (原发布 csdn 2017-10-01 20:02:12)
前言 前段时间使用了net.json保存对象数据.添加完成后,测试发现300多实例数据保存加载json文件,速度比原方式(BinaryFormatter)慢.但是功能加上后也懒再删掉代码了,索性就采用 ...
- day5-python中的序列化与反序列化-json&pickle
一.概述 玩过稍微大型一点的游戏的朋友都知道,很多游戏的存档功能使得我们可以方便地迅速进入上一次退出的状态(包括装备.等级.经验值等在内的一切运行时数据),那么在程序开发中也存在这样的需求:比较简单的 ...
- C# 序列化和反序列化(xml 文件)
序列化是将对象保存为文本文件或二进制文件: 反序列化则是读取文件信息,还原为对象: 序列化保存为文本内容,主要是 xml 和 json 两种,这里介绍序列化为 xml 文件的方式. 想要序列化,先要在 ...
- json数组的序列化和反序列化json数组的序列化和反序列化
如题,我就不多说了,自己看代码的,很好理解 using System; using System.Collections.Generic; using System.Web; using System ...
- Java对象的序列化与反序列化-Json篇
说到Java对象的序列化与反序列化,我们首先想到的应该是Java的Serializable接口,这玩意在两个系统之间的DTO对象里面可能会用到,用于系统之间的数据传输.或者在RPC(远程方法调用)时可 ...
- C# 序列化与反序列化json
与合作伙伴讨论问题,说到的c++与c#数据的转换调用,正好就说到了序列化与反序列化,同样也可用于不同语言间的调用,做了基础示例,作以下整理: using System.Data; using Syst ...
随机推荐
- 使用inpaint例子,去除水印
http://www.opencv.org.cn/forum.php?mod=viewthread&tid=33151 #include "stdafx.h" #inclu ...
- CSS样式与选择器
CSS构造块的样式: 1. h1{color:red;background-color:yellow} 其中:h1是选择器,花括号内是声明部分.多个声明之间用分号隔开. 2.为样式规则添加注释:/* ...
- 获得正在编辑行的数据 esayui datagrid
function getEditRow(datagridId) {//datagridId为table容器的id var input = $('#' + datagridId).parent().fi ...
- sql server 2000/2005递归
/* 递归查询 塗聚文---SQL Server 2005环境下的实现: */--生成测试数据 create table Dept(ID int,ParentID int,msg varchar(20 ...
- caffe的matlab接口一览表
blob 简述 方法: shape reshape get_diff set_diff 私有方法: check_and_preprocess_shape check_and_preprocess_da ...
- Mysql找回root密码
1.停止数据库服务 service mysql stop 2.修改my.cnf 添加skip-grant-tables 3.重启数据库 service mysql restart 4.修改root密码 ...
- masonry框架的使用之-多个视图的均匀等间距分布
__weak typeof(self) weakSelf = self; //对self进行weak化,否则造成循环引用无法释放controller UIView * tempView = [[UIV ...
- jarsigner
开发者应用认领说明 Flyme应用中心应用认领,采用Android的apk安装包签名机制来完成.如果你不清楚签名是什么,请联系开发人员协助您. 在Android平台发布应用程序之前,必须经过一个签名流 ...
- Bookmark
http://stackoverflow.com/https://www.baidu.com/?tn=06074089_27_pghttp://apistore.baidu.com/http://to ...
- 给postgresql 创建新的用户
\du 查看当前postgresql的用户,一般此时只能看到 postgres create user ysr superuser password '123456'; \du 就可以看到两个用户了. ...