如何将 javascript 对象转换成 json字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将 javascript 对象转换成 json字符串相关的知识,希望对你有一定的参考价值。

javascript 对象转换成 json字符串[js对象转换成json字符串]

使用$.toJSON(Object)就可以转换了,转换之前先引入jquery.json.js
/*
* jQuery JSON Plugin
* version: 2.1 (2009-08-14)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
* website\'s http://www.json.org/json2.js, which proclaims:
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
* I uphold.
*
* It is also influenced heavily by MochiKit\'s serializeJSON, which is
* copyrighted 2005 by Bob Ippolito.
*/

(function($)
/** jQuery.toJSON( json-serializble )
Converts the given argument into a JSON respresentation.
If an object has a "toJSON" function, that will be used to get the representation.
Non-integer/string keys are skipped in the object, as are keys that point to a function.
json-serializble:
The *thing* to be converted.
**/
$.toJSON = function(o)

if (typeof(JSON) == \'object\' && JSON.stringify)
return JSON.stringify(o);

var type = typeof(o);

if (o === null)
return "null";

if (type == "undefined")
return undefined;

if (type == "number" || type == "boolean")
return o + "";

if (type == "string")
return $.quoteString(o);

if (type == \'object\')

if (typeof o.toJSON == "function")
return $.toJSON( o.toJSON() );

if (o.constructor === Date)

var month = o.getUTCMonth() + 1;
if (month < 10) month = \'0\' + month;
var day = o.getUTCDate();
if (day < 10) day = \'0\' + day;
var year = o.getUTCFullYear();

var hours = o.getUTCHours();
if (hours < 10) hours = \'0\' + hours;

var minutes = o.getUTCMinutes();
if (minutes < 10) minutes = \'0\' + minutes;

var seconds = o.getUTCSeconds();
if (seconds < 10) seconds = \'0\' + seconds;

var milli = o.getUTCMilliseconds();
if (milli < 100) milli = \'0\' + milli;
if (milli < 10) milli = \'0\' + milli;
return \'"\' + year + \'-\' + month + \'-\' + day + \'T\' +
hours + \':\' + minutes + \':\' + seconds +
\'.\' + milli + \'Z"\';

if (o.constructor === Array)

var ret = [];
for (var i = 0; i < o.length; i++)
ret.push( $.toJSON(o[i]) || "null" );
return "[" + ret.join(",") + "]";


var pairs = [];
for (var k in o)
var name;
var type = typeof k;
if (type == "number")
name = \'"\' + k + \'"\';
else if (type == "string")
name = $.quoteString(k);
else
continue; //skip non-string or number keys

if (typeof o[k] == "function")
continue; //skip pairs where the value is a function.

var val = $.toJSON(o[k]);

pairs.push(name + ":" + val);

return "" + pairs.join(", ") + "";

;
/** jQuery.evalJSON(src)
Evaluates a given piece of json source.
**/
$.evalJSON = function(src)

if (typeof(JSON) == \'object\' && JSON.parse)
return JSON.parse(src);
return eval("(" + src + ")");
;

/** jQuery.secureEvalJSON(src)
Evals JSON in a way that is *more* secure.
**/
$.secureEvalJSON = function(src)

if (typeof(JSON) == \'object\' && JSON.parse)
return JSON.parse(src);

var filtered = src;
filtered = filtered.replace(/\\\\["\\\\\\/bfnrtu]/g, \'@\');
filtered = filtered.replace(/"[^"\\\\\\n\\r]*"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g, \']\');
filtered = filtered.replace(/(?:^|:|,)(?:\\s*\\[)+/g, \'\');

if (/^[\\],:\\s]*$/.test(filtered))
return eval("(" + src + ")");
else
throw new SyntaxError("Error parsing JSON, source is not valid.");
;
/** jQuery.quoteString(string)
Returns a string-repr of a string, escaping quotes intelligently.
Mostly a support function for toJSON.

Examples:
>>> jQuery.quoteString("apple")
"apple"

>>> jQuery.quoteString(\'"Where are we going?", she asked.\')
"\\"Where are we going?\\", she asked."
**/
$.quoteString = function(string)

if (string.match(_escapeable))

return \'"\' + string.replace(_escapeable, function (a)

var c = _meta[a];
if (typeof c === \'string\') return c;
c = a.charCodeAt();
return \'\\\\u00\' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
) + \'"\';

return \'"\' + string + \'"\';
;

var _escapeable = /["\\\\\\x00-\\x1f\\x7f-\\x9f]/g;

var _meta =
\'\\b\': \'\\\\b\',
\'\\t\': \'\\\\t\',
\'\\n\': \'\\\\n\',
\'\\f\': \'\\\\f\',
\'\\r\': \'\\\\r\',
\'"\' : \'\\\\"\',
\'\\\\\': \'\\\\\\\\\'
;
)(jQuery);
参考技术A 方法如下:
1 换回字符串
var myObjectInJSON = myObject.toJSONString();//也没有这个方法
var jsonStr = JSON.stringify( obj );
var jsonStr = jQuery.stringifyJSON(obj);//没有这个方法,误导我
2 转为json对象
var bToObj=JSON.parse(b);
jQuery.parseJSON(json);
var c='"name":"Mike","sex":"女","age":"29"';
var jsonObj=eval("("+c+")");
参考技术B JSON.stringify(obj);

如何将C#/.NET 将json字符串格式数据转换成对象?

参考技术A 下个Newtonsoft.Json插件
引用 Newtonsoft.Json.dll

1、json字符串
string xxx = "\"count\":\"1\",\"Product_Code\":\"14003949\",\"Product_Name\":\"聚丙烯树脂\",\"Product_Batch\":\"20140228D8103\",\"Certification_Code\":\"SCSH20140226-001-01\",\"Plate_Code\":\"L5E-89\",\"Grade\":\"合格品\",\"WarehouseIn_Num\":\"19120.0000000\",\"WarehouseIn_Weight\":\"478.000\",\"WarehouseIn_Confirm_Date\":\"2014-03-01\"";

则直接转换为对象:

M_WarehouseInResult whh = JsonConvert.DeserializeObject<M_WarehouseInResult>(xxx);
2、如果为json数组(注意:最外是中括号)
string xxx = "[\"count\":\"1\",\"Product_Code\":\"14003949\",\"Product_Name\":\"聚丙烯树脂\",\"Product_Batch\":\"20140228D8103\",\"Certification_Code\":\"SCSH20140226-001-01\",\"Plate_Code\":\"L5E-89\",\"Grade\":\"合格品\",\"WarehouseIn_Num\":\"19120.0000000\",\"WarehouseIn_Weight\":\"478.000\",\"WarehouseIn_Confirm_Date\":\"2014-03-01\"]";

json数组转换为list

List<M_WarehouseInResult> whh = JsonConvert.DeserializeObject<List<M_WarehouseInResult>>(xxx);

附:
public class M_WarehouseInResult

public string count get; set;
public string Product_Code get; set;
public string Product_Name get; set;
public string Product_Batch get; set;
public string Certification_Code get; set;
public string Plate_Code get; set;
public string Grade get; set;
public string WarehouseIn_Num get; set;
public string WarehouseIn_Weight get; set;
public string WarehouseIn_Confirm_Date get; set;
参考技术B

首先你要按JSON的结构定义一个类,类中的变量要用属性的形式.


也就是public String XXget;set;这样.


然后可以参考我下面的代码,是在.NET 4.6下面写的,好像3.5和4.0要用另一个类.


1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


26


27


28


using System;


using System.Collections.Generic;


using System.IO;


using System.Linq;


using System.Runtime.Serialization.Json;


using System.Text;


using System.Web;



namespace XXX



public class clsJson



public static T Deserialize<T>(String s) where T : class



DataContractJsonSerializer dataContractJsonSerializer = new 

DataContractJsonSerializer(typeof(T));


MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(s));


return dataContractJsonSerializer.ReadObject(memoryStream) as T;





public static String Serialize<T>(T t) where T : class



DataContractJsonSerializer dataContractJsonSerializer = new 

DataContractJsonSerializer(typeof(T));


MemoryStream memoryStream = new MemoryStream();


dataContractJsonSerializer.WriteObject(memoryStream, t);


return Encoding.UTF8.GetString(memoryStream.ToArray(), 0, 

Convert.ToInt32(memoryStream.Length));





参考技术C

json作为作为一种最常用的数据,应用很广泛,在.net中如何把一个对象转化为json字符串呢?

主要有一下几种

1按照json的定义自己转化,难度很大,但很灵活。需要自己处理各种特殊字符,各种数据类型

2使用开源的类库Newtonsoft.Json

3使用JavaScriptSerializer类 

4使用System.Runtime.Serialization.dll提供的DataContractJsonSerializer或者 JsonReaderWriterFactory实现。

1按照json的定义自己转化,难度很大,但很灵活。需要自己处理各种特殊字符,各种数据类型

要写成通用的核心就是使用反射。

2使用开源的类库Newtonsoft.Json,很方便,.net的各个版本都有。

/// <summary>

/// 对象转为json

/// </summary>

/// <typeparam name="ObjType"></typeparam>

/// <param name="obj"></param>

/// <returns></returns>

public static string ObjToJsonString<ObjType>(ObjType obj) where ObjType : class

string s = JsonConvert.SerializeObject(obj);

return s;

/// <summary>

/// json转为对象

/// </summary>

/// <typeparam name="ObjType"></typeparam>

/// <param name="JsonString"></param>

/// <returns></returns>

public static ObjType JsonStringToObj<ObjType>(string JsonString) where ObjType : class

         

ObjType s = JsonConvert.DeserializeObject<ObjType>(JsonString);

return s;

3JavaScriptSerializer类 ,使用.NET Framework 3.5/4.0中提供的System.Web.Script.Serialization命名空间下的JavaScriptSerializer类进行对象的序列化与反序列化。需要添加程序集System.Web.Extensions.dll。

/// <summary>

/// 对象转为json

/// </summary>

/// <typeparam name="ObjType"></typeparam>

/// <param name="obj"></param>

/// <returns></returns>

public static string ObjToJsonString<ObjType>(ObjType obj) where ObjType : class

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

string s = jsonSerializer.Serialize(obj);

return s;

 

/// <summary>

/// json转为对象

/// </summary>

/// <typeparam name="ObjType"></typeparam>

/// <param name="JsonString"></param>

/// <returns></returns>

public static ObjType JsonStringToObj<ObjType>(string JsonString) where ObjType : class

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

ObjType s = jsonSerializer.Deserialize<ObjType>(JsonString);

return s;

4使用System.Runtime.Serialization.dll提供的DataContractJsonSerializer或者 JsonReaderWriterFactory实现。

具体可参考

阅读全文

1 0

上一篇 下一篇

暂无评论,我去发表~

C# 中对象与Json互转的方法整理笔记

 xymaco 2014-09-05 19:13 10474

最新C# Object与json互转

 chenjiazhu 2016-07-20 20:19 10494

C# JSON串和对象互相转换

 jn1705 2011-06-22 15:30 13791

C# json字符串转为对象及JavaScriptSerializer:

 ma15732625261 2016-08-07 17:56 1346

C# .Net 将Json转成.Net对象

 voodooer 2012-12-27 09:39 8481

使用FastJSON,将对象或数组和JSON串互转

 gaojinshan 2014-06-12 16:42 184270

如何将C#/.NET 将json字符串格式数据转换成对象

 killcwd 2015-03-27 11:13 2384

JSON.NET框架实现C#对象和JSON字符串的转换

 ful1021 2014-08-18 11:04 1658

 未登录

•首页

•人工智能

•移动开发

•物联网

•架构

•云计算/大数据

•互联网

•游戏开发

•运维

•数据库

•前端

•后端

•编程语言

•研发管理

•安全

•程序人生

•区块链

•音视频开发

•资讯

•计算机理论与基础

•综合

以上是关于如何将 javascript 对象转换成 json字符串的主要内容,如果未能解决你的问题,请参考以下文章

如何将 javascript 对象转换成 json字符串

javascript如何将一个字符串转换为一个对象?

JavaScript查漏补缺 —对象转换成字符串JSON.stringify()

csv转换obj

java调用javascript时,如何将NativeArray或NativeObject转换成java实体或者HashMap,List对象

php如何将json对象转字符串