文档库 最新最全的文档下载
当前位置:文档库 › JSON解析详细文档

JSON解析详细文档

JSON解析详细文档
JSON解析详细文档

JSON 的含义?

JSON的全称是JavaScript Object Notation,是一种轻量级的数据交换格式。JS ON与XML具有相同的特性,例如易于人编写和阅读,易于机器生成和解析。但是JSON 比XML数据传输的有效性要高出很多。JSON完全独立与编程语言,使用文本格式保存。

JSON数据有两种结构:

?Name-Value 对构成的集合,类似于Java中的Map。

?Value的有序列表,类似于Java中的Array。

一个JSON格式的数据示例:

{

"Name": "Apple",

"Expiry": "2007/10/11 13:54",

"Price": 3.99,

"Sizes": [

"Small",

"Medium",

"Large"

]

}

更多关于JSON数据格式的说明参看JSON官方网站:https://www.wendangku.net/doc/fb5980634.html,(中文内容参看:https://www.wendangku.net/doc/fb5980634.html,/json-zh.html)

GWT与JSON

GWT中支持的客户端服务器端方法调用和数据传递的标准格式是RPC。 JSON并不是GWT支持的标准的数据传递格式。那么如何使用JSON来作为GWT的数据传递格式呢?需要以下几步。

第一,引用HTTP和JSON支持。

第二,在客户端创建JSON数据,提交到服务器

第三,在服务器上重写数据格式解析的代码,使之支持JSON格式的数据

第四,在服务器上组织JSON格式的数据,返回给客户端。

第五,客户端解析服务器传回的JSON数据,正确的显示

引用HTTP和JSON支持

找到.gwt.xml文件,在其中的

在之后添加如下的内容:

其中com.google.gwt.json.JSON指的是要使用JSON,com.google.gwt.http.H TTP值得是通过HTTP调用服务器上的服务方法。

客户端构造JSON数据

客户端需要使用com.google.gwt.json.client包内的类来组装JSON格式的数据,数据格式如下:

数据类型说明

JSONArray JSONValue构成的数组类型

JSONBoolean JSON boolean值

访问JSON结构的数据出错的情况下可以抛出此异JSONException

JSONNull JSON Null根式的数据

JSONNumber JSON Number类型的数据

JSONObject JSON Object类型的数据

将String格式的JSON数据解析为JSONValue类JSONParser

型的数据

JSONString JSON String类型的数据

JSONValue 所有JSON类型值的超级类型组合一个简单的JSON数据:

JSONObject input = new JSONObject();

JSONString value = new JSONString("mazhao");

input.put("name", value);

JSON数据格式为:{name: "mazhao"}

组合一个包含数组类型的复杂JSON数据:

JSONObject input = new JSONObject();

JSONString value = new JSONString("mazhao");

input.put("name", value);

JSONArray arrayValue = new JSONArray();

arrayValue.set(0, new JSONString("array item 0"));

arrayValue.set(1, new JSONString("array item 1"));

arrayValue.set(2, new JSONString("array item 2"));

input.put("array", arrayValue);

JSON数据格式为:

{name: "mazhao",

array: {"array item 0", "array item 1", "array item 2"}}

注意上述的JSON类型的数据,使用的都是com.google.gwt.json.client包内的类型。这些类型最终会被编译为JavaScript执行。

服务端重写数据解析代码,支持JSON格式的数据

在服务器上,需要使用JSON Java支持类才能将JSON格式的数据转换为各种类型的数据,当然也可以自己写一些解析用的代码。这里我们使用了https://www.wendangku.net/doc/fb5980634.html,上的代码来完成。这组代码与com.google.gwt.json.client的代码很相似,只是在org.json包内部。

怎么解析JSON术诀呢?针对上述中的复杂的JSON数据:

{name: "mazhao",

array: {"array item 0", "array item 1", "array item 2"}}

可以使用如下的方式解析:

JSONObject jsonObject = new JSONObject(payload);

String name = jsonObject.getString("name");

System.out.println("name is:" + name);

JSONArray jsonArray = jsonObject.getJSONArray("array");

for(int i = 0; i < jsonArray.length(); i++) {

System.out.println("item " + i + " :" + jsonArray.getString(i));

}

其中payload指的是上述的JSON格式的数据。

那么如何写GWT 的Service来得到Payload的数据呢?需要两点,第一,需要建立一个Service类,第二,覆盖父类的processCall方法。

示例代码:

package com.jpleasure.gwt.json.server;

import https://www.wendangku.net/doc/fb5980634.html,er.client.rpc.SerializationException;

import https://www.wendangku.net/doc/fb5980634.html,er.server.rpc.RemoteServiceServlet;

import com.jpleasure.gwt.json.client.HelloWorldService;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

/**

* Created by IntelliJ IDEA.

* User: vaio

* Date: 2007-9-4

* Time: 22:08:31

* To change this template use File | Settings | File Templates.

*/

public class HelloWorldServiceImpl extends RemoteServiceServlet implemen ts HelloWorldService {

public String processCall(String payload) throws SerializationException { try {

JSONObject jsonObject = new JSONObject(payload);

String name = jsonObject.getString("name");

System.out.println("name is:" + name);

JSONArray jsonArray = jsonObject.getJSONArray("array");

for(int i = 0; i < jsonArray.length(); i++) {

System.out.println("item " + i + " :" + jsonArray.getString(i));

}

} catch (JSONException e) {

e.printStackTrace(); //To change body of catch statement use File

| Settings | File Templates.

}

return "success";

}

}

在服务器上组织JSON格式的数据,返回给客户端

同上

客户端解析服务器传回的JSON数据,正确的显示

同上

Struts2返回json需要jsonplugin-0[1].25的

然后我们的配置文件中需要继承json-default

Java代码

1.

2.

3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//

EN"

4. "https://www.wendangku.net/doc/fb5980634.html,/dtds/struts-2.0.dtd">

5.

6.

7.

8.

espace="/" >

9.

10.

11.

12.

13.

14.

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"https://www.wendangku.net/doc/fb5980634.html,/dtds/struts-2.0.dtd">

然后我们的Action中需要返回的json信息需要加上注解

Java代码

1.//pizza

2.package com.action.testJson;

3.

4.import java.util.ArrayList;

5.import java.util.List;

6.

7.import com.googlecode.jsonplugin.annotations.JSON;

8.import com.opensymphony.xwork2.ActionSupport;

9.

10.p ublic class JsonAction extends ActionSupport {

11.

12. private static final long serialVersionUID = -4082165361641669835

L;

13.

14. Users user=new Users();

15. List userList=new ArrayList();

16.

17.

18. public String testUser(){

19. System.out.println("in the json Acton");

20. userInit();

21. userList.add(user);

22. return SUCCESS;

23. }

24.

25. public void userInit(){

26. user.setAge(1);

27. user.setName("张泽峰");

28. user.setPassword("nofengPassword");

29. }

30.

31. @JSON(name="userString")

32. public Users getUser() {

33. return user;

34. }

35.

36. @JSON(name="userList")

37. public List getUserList() {

38. return userList;

39. }

40.

41. public void setUser(Users user) {

42. https://www.wendangku.net/doc/fb5980634.html,er = user;

43. }

44.

45. public void setUserList(List userList) {

46. https://www.wendangku.net/doc/fb5980634.html,erList = userList;

47. }

48.

49.

50.}

JSON Plugin

的说明

Edit Page Browse Space Add Page Add News Added by Musac hy Barroso, last edited by ghostr oller on Jul 04, 2008 (view change) SHOW COMMENT

Name JSON Plugin

Publisher Musachy Barroso

License Open Source (ASL2)

Version 0.30

Compatibility Struts 2.0.6 or la ter

Homepage https://www.wendangku.net/doc/fb5980634.html,/p/jsonplugin/

Download https://www.wendangku.net/doc/fb5980634.html,/p/jsonplugin/downloads/list

Rating? 1 2 3 4 5

Overview

The JSON plugin provides a "json" result type that serializes actions into JSON. The serialization process is recursive, meaning that the whole object graph, starting on the action class (base class not included) will be serialized (root object can be customized using the "root" attribute). If the interceptor is used, the action will be populated from the JSON content in the request, these are the rules of the interceptor:

1.The "content-type" must be "application/json"

2.The JSON content must be well formed, see https://www.wendangku.net/doc/fb5980634.html, for grammar.

3.Action must have a public "setter" method for fields that must be popula ted.

4.Supported types for population are: Primitives (int,long...String), Date, List, Map,

Primitive Arrays, Other class (more on this later), and Array of Other class.

5.Any object in JSON, that is to be populated inside a list, or a map, will be of type Map

(mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.

Given this JSON string:

{

"doubleValue": 10.10,

"nestedBean": {

"name": "Mr Bean"

},

"list": ["A", 10, 20.20, {

"firstName": "El Zorro"

}],

"array": [10, 20]

}

The action must have a "setDoubleValue" method, taking either a "float" or a "double" argument (the interceptor will convert the value to the right one). There must be a "setNeste dBean" whose argument type can be any class, that has a "setName" method taking as argument an "String". There must be a "setList" method that takes a "List" as argument, that list will contain: "A" (S tring), 10 (Long), 20.20 (Double), Map ("firstName" -> "El Zorro"). The "setArray" method can take as parameter either a "List", or any numeric array.

Installation

This plugin can be installed by copying the plugin jar into your application's /WEB-INF/lib directory. No other files need to be copied or created.

To use maven, add this to your pom:

...

com.googlecode

jsonplugin

0.26

...

Maven Plugin Repository

https://www.wendangku.net/doc/fb5980634.html,/svn/trunk/

false

true

Customizing Serialization and Deserialization

Use the JSON annotation to customize the serialization/deserialization process. Available JSON annotation fields:

Name Description Default Value Serialization Deserialization name Customize field name empty yes no serialize Include in serialization true yes no

deserialize

Include in

deserialization

true no yes

format Format used to "yyyy-MM-dd'T'HH:mm:ss" yes yes

format/parse a Date

field

Excluding properties

A comma-delimited list of regular expressions can be passed to the JSON Result and Interceptor, properties matching any of these regular expressions will be ignored on the serialization process:

login.password,

studentList.*\.sin

true

login.password,

studentList.*\.sin

Including properties

A comma-delimited list of regular expressions can be passed to the JSON Result to restrict which properties will be serialized. ONLY properties matching any of these regular expressions will be included in the serialized output.

Note

Exclude property expressions take precedence over include property

expressions. That is, if you use include and exclude property expressions on

the same result, include property expressions will not be applied if an exclude

exclude property expression matches a property first.

^entries\[\d+\]\.clientNumber,

^entries\[\d+\]\.scheduleNumber,

^entries\[\d+\]\.createUserId

Root Object

Use the "root" attribute(OGNL expression) to specify the root object to be serialized.

person.job

The "root" attribute(OGNL expression) can also be used on the interceptor to specify the object that must be populated, make sure this object is not null.

bean1.bean2

Wrap with Comments

wrapWithComments can turn safe JSON text into dangerous text. For

example,

["*/ alert('XSS'); /*"]

Thanks to Douglas Crockford for the tip!

If the "wrapWithComments" (false by default) attribute is set to true, the generated JSON is wrapped with comments like:

/* {

"doubleVal": 10.10,

"nestedBean": {

"name": "Mr Bean"

},

"list": ["A", 10, 20.20, {

"firstName": "El Zorro"

}],

"array": [10, 20]

} */

This can be used to avoid potential Javascript Hijacks. To strip those comments use:

var responseObject = eval("("+data.substring(data.indexOf("\/\*")+2, https://www.wendangku.net/doc/fb5980634.html,stIndexOf("\*\/"))+")");

Base Classes

By default properties defined on base classes of the "root" object won't be serialized, to serialize properties in all base classes (up to Object) set "ignoreHierarchy" to false in the JSON result:

false

Enumerations

By default, an Enum is serialized as a name=value pair where value = name().

public enum AnEnum {

ValueA,

ValueB

}

JSON: "myEnum":"ValueA"

Use the "enumAsBean" result parameter to serialize Enum's as a bean with a special property _name with value name(). All properties of the enum are also serialized.

public enum AnEnum {

ValueA("A"),

ValueB("B");

private String val;

public AnEnum(val) {

this.val = val;

}

public getVal() {

return val;

}

}

JSON: myEnum: { "_name": "ValueA", "val": "A" }

Enable this parameter through struts.xml:

true

Compressing the output.

Set the enableGZIP attribute to true to gzip the generated json response. The request must include "gzip" in the "Accept-Encoding" header for this to work.

true

Example

Setup Action

This simple action has some fields:

Example:

import java.util.HashMap;

import java.util.Map;

import com.opensymphony.xwork2.Action;

public class JSONExample {

private String field1 = "str";

private int[] ints = {10, 20};

private Map map = new HashMap();

private String customName = "custom";

//'transient' fields are not serialized

private transient String field2;

//fields without getter method are not serialized

private String field3;

public String execute() {

map.put("John", "Galt");

return Action.SUCCESS;

}

public String getField1() {

return field1;

}

public void setField1(String field1) {

this.field1 = field1;

}

public int[] getInts() {

return ints;

}

public void setInts(int[] ints) {

this.ints = ints;

}

public Map getMap() {

return map;

}

public void setMap(Map map) {

this.map = map;

}

@JSON(name="newName")

public String getCustomName() {

return this.customName;

}

}

Write the mapping for the action

1.Add the map inside a package that extends "json-default"

2.Add a result of type "json"

Example:

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"https://www.wendangku.net/doc/fb5980634.html,/dtds/struts-2.0.dtd">

JSON example output

{

"field1" : "str",

"ints": [10, 20],

"map": {

"John":"Galt"

},

"newName": "custom"

}

JSON RPC

The json plugin can be used to execute action methods from javascript and return the output. This feature was developed with Dojo in mind, so it uses Simple Method Definition to advertise the remote service. Let's work it out with an example(useless as most examples).

First write the action:

package smd;

import com.googlecode.jsonplugin.annotations.SMDMethod;

import com.opensymphony.xwork2.Action;

public class SMDAction {

public String smd() {

return Action.SUCCESS;

}

@SMDMethod

public Bean doSomething(Bean bean, int quantity) {

bean.setPrice(quantity * 10);

return bean;

}

}

Methods that will be called remotely must be annotated with the SMDMethod annotation, for security reasons. The method will take a bean object, modify its price and return it. The action can be annotated with the SMD annota tion to customize the generated SMD (more on that soon), and parameters can be annotated with SMDMethodParameter. As you can see, we have a "dummy", smd method. This method will be used to generate the Simple Method Definition (a definition of all

the services provided by this class), using the "json" result.

The bean class:

package smd;

public class Bean {

private String type;

private int price;

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public int getPrice() {

return price;

}

public void setPrice(int price) {

this.price = price;

}

}

The mapping:

true

true

Nothing special here, except that both the interceptor and the result must be applied to the action, and "enableSMD" must be enabled for both.

Now the javascript code:

Dojo's JsonService will make a request to the action to load the SMD, which will return a JSON object with the definition of the available remote methods, using tha t information Dojo creates a "proxy" for those methods. Because of the asynchronous nature of the request, when the m ethod is executed, a deferred object is returned, to which a callback function can be attached. The callback function will receive as a parameter the object returned from your action. That's it.

Proxied objects

(V0.20) As annotations are not inherited in Java, some user might experience problems while trying to serialize objects that are proxied. eg. when you have attached AOP interceptors to your action.

In this situa tion, the plugin will not detect the annota tions on methods in your action.

To overcome this, set the "ignoreInterfaces" result parameter to false (true by default) to request that the plugin inspects all interfaces and superclasses of the action for annota tions on the action's methods.

NOTE: This parameter should only be set to false if your action could be a proxy as there is a performance cost caused by recursion through the interfaces.

true

false

true

false

在Struts 2中使用JSon ajax支持

来源:作者:发布时间:2007-12-19

JSON插件提供了一种名为json的ResultType,一旦为某个Action指定了一个类型为json的Result,则该Result无需映射到任何视图资源。因为JSON 插件会负责将Action里的状态信息序列化成JSON格式的数据,并将该数据返回给客户端页面的JavaScript。

简单地说,JSON插件允许我们在JavaScript中异步调用Action,而且Action 不再需要使用视图资源来显示该Action里的状态信息,而是由JSON插件负责将Action里的状态信息返回给调用页面——通过这种方式,就能够完成Ajax 交互。

Struts2提供了一种可插拔方式来管理插件,安装Struts2的JSON插件和安装普通插件并没有太大的区别,相同只需要将Struts2插件的JAR文档复制到Web应用的WEB-INF/lib路径下即可。

安装JSON插件按如下步骤进行:

(1)登陆https://www.wendangku.net/doc/fb5980634.html,/p/jsonplugin/downloads/list站点,下载Struts2的JSON插件的最新版本,当前最新版本是0.7,我们能够下载该版本的JSON 插件。

(2)将下载到的jsonplugin-0.7.jar文档复制到Web应用的WEB-INF路径下,即可完成JSON插件的安装。

实现Actio逻辑

假设wo,en输入页面中包含了三个表单域,这三个表单域对于三个请求参数,因此应该使用Action来封装这三个请求参数。三个表单域的name分别为field1、field2和field3。

处理该请求的Action类代码如下:

public class JSONExample

{

//封装请求参数的三个属性

private String field1;

private transient String field2;

private String field3;

//封装处理结果的属性

private int[] ints = {10, 20};

private Map map = new HashMap();

private String customName = "custom";

//三个请求参数对应的setter和getter方法

public String getField1()

{

return field1;

}

public void setField1(String field1)

{

this.field1 = field1;

}

//此处省略了field1和field2两个字段的setter和getter方法

...

//封装处理结果的属性的setter和getter方法

public int[] getInts()

{

return ints;

}

public void setInts(int[] ints)

{

this.ints = ints;

}

public Map getMap()

{

return map;

}

public void setMap(Map map)

{

this.map = map;

}

//使用注释语法来改变该属性序列化后的属性名

@JSON(name="newName")

public String getCustomName()

{

return this.customName;

}

public String execute()

{

map.put("name", "yeeku");

return Action.SUCCESS;

}

}

在上面代码中,使用了JSON注释,注释时指定了name域,name域指定Action属性被序列化成JSON对象的属性名。除此之外,JSON注释还支持如下几个域:

serialize:配置是否序列化该属性

deserialize:配置是否反序列化该属性。

format:配置用于格式化输出、解析日期表单域的格式。例如

"yyyy-MM-dd'T'HH:mm:ss"。

配置该Action和配置普通Action存在小小的区别,应该为该Action配置类型为json的Result。而这个Result无需配置任何视图资源。

配置该Action的struts.xml文档代码如下:

<?xml version="1.0" encoding="GBK"?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"https://www.wendangku.net/doc/fb5980634.html,/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.i18n.encoding" value="UTF-8"/>

<package name="example" extends="json-default">

<action name="JSONExample" class="lee.JSONExample">

<result type="json"/>

</action>

</package>

</struts>

在上面配置文档中有两个值得注意的地方:

第一个地方是配置struts.i18n.encoding常量时,不再是使用GBK编码,而

后台转换JSON数据类型,前台解析JSON数据等等例子总结

后台转换JSON数据类型,前台解析JSON数据等等例子总结 JSON对象: JSONObject obj = new JSONObject(); obj.put("result", 0); obj.put("message", message); return obj.toJSONString(); 前台解析: Success:function(data){ var result = data.result; var message = data.message; } json对象中有json对象的写法: Objstr为一个JSONObject obj的String转换 private String getsuccess(String objstr,int number){ JSONObject obj = new JSONObject(); obj.put("result", 1); obj.put("obj", objstr); obj.put("number", number); return obj.toJSONString(); }

前台解析: Picjson为success返回的data var result = picjson.result; if (result==1) { var objdata = picjson.obj; var data = eval('(' + objdata + ')'); var num = picjson.number; picurl = null; showpiclist(data, num); } else{ alert(picjson.message); picurl = null; } list转成json对象 需要的包: https://www.wendangku.net/doc/fb5980634.html,mons-lang.jar https://www.wendangku.net/doc/fb5980634.html,mons-beanutils.jar https://www.wendangku.net/doc/fb5980634.html,mons-collections.jar https://www.wendangku.net/doc/fb5980634.html,mons-logging.jar

Json数据格式的使用方法入门教程

JSON 数据格式解析 和 XML 一样,JSON 也是基于纯文本的数据格式。由于 JSON 天生是为JavaScript 准备的,因此,JSON 的数据格式非常简单,您可以用 JSON 传输一个简单的 String,Number,Boolean,也可以传输一个数组,或者一个复杂的Object 对象。 String,Number 和 Boolean 用 JSON 表示非常简单。例如,用 JSON 表示一个简单的 String “ abc ”,其格式为: "abc" 除了字符 ",\,/ 和一些控制符(\b,\f,\n,\r,\t)需要编码外,其他 Unicode 字符可以直接输出。下图是一个 String 的完整表示结构: 图 1. String 的完整表示结构 一个 Number 可以根据整型或浮点数表示如下:

图 2. Number 的表示结构 这与绝大多数编程语言的表示方法一致,例如: 12345(整数) -3.9e10(浮点数) Boolean 类型表示为 true 或 false 。此外,JavaScript 中的 null 被表示为 null,注意,true、false 和 null 都没有双引号,否则将被视为一个String 。 JSON 还可以表示一个数组对象,使用 [] 包含所有元素,每个元素用逗号分隔,元素可以是任意的 Value,例如,以下数组包含了一个 String,Number,Boolean 和一个 null: Object 对象在 JSON 中是用 {} 包含一系列无序的 Key-Value 键值对表示的,实际上此处的 Object 相当于 Java 中的 Map,而不是Java 的 Class 。注意 Key 只能用 String 表示。 例如,一个 Address 对象包含如下 Key-Value:

标准JSON格式定义与解析注意点

是一种轻量级地数据交换格式.它是基于语法标准地一个子集.是一种轻量级地数据交换格式.采用完全独立于语言地文本格式,可以很容易在各种网络、平台和程序之间传输.地语法很简单,易于人阅读和编写,同时也易于机器解析和生成. 要想熟练地操作数据,就要先了解数据: 地规则很简单:对象是一个无序地“‘名称值’对”集合.一个对象以“{”(左括号)开始,“}”(右括号)结束.每个“名称”后跟一个“:”(冒号);“‘名称值’对”之间使用“,”(逗号)分隔.文档来自于网络搜索 规则如下: 、映射用冒号(“:)表示.名称:值 、并列地数据之间用逗号(“,”)分隔.名称:值,名称:值 、映射地集合(对象)用大括号(“{}”)表示. { 名称:值, 名称:值 } 、并列数据地集合(数组)用方括号(“[]”)表示. [ {名称:值,名称:值}, {名称:值,名称:值} ] 、元素值可具有地类型:, , , , , 文档来自于网络搜索 注意:、用冒号(而不是等号)来赋值.每一条赋值语句用逗号分开.整个对象用大括号封装起来.可用大括号分级嵌套数据.文档来自于网络搜索 、对象描述中存储地数据可以是字符串,数字或者布尔值.对象描述也可存储函数,那就是对象地方法. 、主要有两种数据结构 ()由–对组成地数据结构.这种数据结构在不同地语言中有不同地实现. 例如:在中是一个对象.而在中是一种结构语言中是,其它地语言中可能为、等.文档来自于网络搜索 ()有序集合、这种数据结构在不同语言中可能有、、数组和序列等实现. 、中数据格式地处理 <>转 [] <>( ) {

{ (()); 文档来自于网络搜索( ()) { (, ); (()); } } { ; } } 转<> [] ( ) { { (); 文档来自于网络搜索 ( (())) 文档来自于网络搜索 { (); } } { ; } } 转 [] ( ) { ( ) { ""; } ();

js读取解析JSON数据

js读取解析JSON数据 各位读友大家好!你有你的木棉,我有我的文章,为了你的木棉,应读我的文章!若为比翼双飞鸟,定是人间有情人!若读此篇优秀文,必成天上比翼鸟! js读取解析JSON数据js读取解析JSON数据JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式。同时,JSON是JavaScript 原生格式,这意味着在JavaScript 中处理JSON数据不须要任何特殊的API 或工具包。本文主要是对JS操作JSON的要领做下总结。在JSON中,有两种结构:对象和数组。1. 一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’对”之间运用“,”(逗号)分隔。名称用引号括起来;值如果是字符串则必须用括号,数值型则不须要。例如:var o={“xlid”:”cxh”,”xldigitid”:123456,”topscore”:2000,”topplaytime”:”2009-08-20”};2. 数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间运用“,”(逗号)分隔。例如:var jsonranklist=[{“xlid”:”cxh”,”xldigitid”:123456,”topscore”:2000,”top playtime”:”2009-08-20”},{“xlid”:”zd”,”xldigitid”:123456,”topscore ”:1500,”topplaytime”:”2009-11-20”}];为了方便地处理JSON数据,JSON提供了json.js包,下载地址:https://www.wendangku.net/doc/fb5980634.html,/json.js在

JSON的List数据封装解析方案

对象封装成为List和JSON解析成封装有对象的List 1、封装方法类(将JSONArray放入JSONObject中发给客户端) package com.mlp.tools; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import https://www.wendangku.net/doc/fb5980634.html,ebean.Messages; import https://www.wendangku.net/doc/fb5980634.html,ebean.Resources; import https://www.wendangku.net/doc/fb5980634.html,ebean.Types; public class ListToJSONArray { public static JSONArray setListToJR(ArrayList list){ JSONObject json=null; JSONArray ja=new JSONArray(); for(int i=0;i list){ JSONObject json=null;

androidjson解析及简单例子(转载).

JSON 的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持,从而可以在不同平台间进行数据交换。 JSON 采用兼容性很高的文本格式,同时也具备类似于 C 语言体系的行为。– https://www.wendangku.net/doc/fb5980634.html, JSON Vs XML 1.JSON 和 XML 的数据可读性基本相同 2.JSON 和 XML 同样拥有丰富的解析手段 3.JSON 相对于 XML 来讲,数据的体积小 4.JSON 与 JavaScript 的交互更加方便 5.JSON 对数据的描述性比 XML 较差 6.JSON 的速度要远远快于 XML android2.3提供的 json 解析类 android 的 json 解析部分都在包 org.json 下,主要有以下几个类: JSONObject :可以看作是一个 json 对象 , 这是系统中有关 JSON 定义的基本单元, 其包含一对儿 (Key/Value数值。它对外部 (External:应用 toString(方法输出的数值调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的 Key 和 Value 被冒号 ":"分隔。其对于内部 (Internal行为的操作格式略微,例如:初始化一个 JSONObject 实例,引用内部的 put(方法添加数值:new JSONObject(.put("JSON", "Hello, World!", 在 Key 和 Value 之间是以逗号 "," 分隔。Value 的类型包括:Boolean 、 JSONArray 、 JSONObject 、 Number 、 String 或者默认值 JSONObject.NULL object 。

java中解析json的三种方式

//第一种 public void jsonTx() { String json = "{'status':200,'message':'查询成功','data':[{'id':1,'name':'name1','describe':'第一条数据'}]}"; JSONObject data = new JSONObject(json); int status = data.optInt("status"); JSONArray data1 = data.getJSONArray("data"); if (status==200) { for(int i=0;i

JSONObject详解及用法

一、JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写。同时,也易于机器解析和生成。 二、JSON数据格式解析:和XML一样,JSON也是基于存文本的数据格式。您可以用JSON传输一个简单的String、Number、Boolean,也可以传输一个数组或者一个复杂的Object对象。例如:1、用JSON表示一个简单String “abc”,其格式为:”abc”。除了字符“,\,/ 和一些控制符(\b,\n,\t 等)需要编码外,其他Unicode字符可以直接输出。 2、用JSON表示一个数组对象,使用“[ ]“包含所有元素,每个元素用逗号分隔,元素可以使任意的value,例如,一下数组包含了一个String、Number、Boolean、和一个null:[“abc”,123,false,null]。 3、Object对象在JSON中用“{ }“包含一系列无序的Key-Value键值对表示,实际上此处的Object相当于Java 中的Map。注意Key只能用String表示。例如:一个Address对象包含如下Key-Value:{“city”:”beijing”,”street”:”chaoyang”,”postcode”:100025}。 三、JAVASCRIPT处理JSON数据Function demo(){ var v={“name”:”SMITH”,”address”: {“city”:”beijing”,”street”:”chaoyang”,”postcode”:100025}}; document.write(https://www.wendangku.net/doc/fb5980634.html,); document.write(v.address.city); } 四:JSON和XML的比较XML和JSON都是用结构化方法来标记数据,下面来做一个简单的比较。 中国 黑龙江 哈尔滨 大庆 用JSON表示如下:{ name:”中国”,province:[ { Name:”黑龙江”,citys:{“哈尔滨”,”大庆”} } ]

json数据解析

这个方法是参考 https://www.wendangku.net/doc/fb5980634.html,/networking-database-problems-f29/connecting-to-mysql-database-t50063.html 国外老外的一些经验所得。这里我总结一下要点: 1、需要一个mysql数据库,这个怎么搞出来,大家觉得有问题先学学mysql再回来接着看。 2、需要一个php操作mysql数据库的脚本,上传到服务器地址 3、需要修改Android的manifest文件,入网许可!! 一、首先我们假如已经把MYSQL数据库建立好了,写一个PHP操作文件上传到服务器访问地址 [php]view plaincopyprint? 1 稍微解析一下上面PHP内容, [php]view plaincopyprint? 10$q=mysql_query("SELECT * FROM user_info WHERE uName ='".$_REQUEST['name']."'"); 这句当中 [php]view plaincopyprint? 11.$_REQUEST['name']. 就表示要从android里面输入到这里的一个键值对的值,id为name,下面我们 写Android程序会再说明一下。 [php]view plaincopyprint?

Json解析详细教程

Json 解析详细教程 1、JSON(JavaScript Object Notation) 定义: 轻量级的数据交换格式,具有良好的可读和便于快速编写的 特性。业内主流技术为其提供了完整的解决方案(有点类似 于正则表达式,获得了当今大部分语言的支持) ,从而可以 在不同平台间进行数据交换。 JSON 采用兼容性很高的文本 { "name":"小猪","age":20 } Array Array 是值(value )的有序集合。 [value , value , value ] 值(value )可以是双引号括起来的字符串(string )、数值 (number )、true 、false 、null 、对象(object )或者数组 (array )。 这些结构可以嵌套。 字符串(string )是由双弓 包围的任意数量 Unicode 字符的集合,使用反斜线转义。 个字符(character )即一个单独的字符串(character string )。 例如: \ + " \ / b f n r t u 进行转义。 例子 1: Array 里 格式,同时也具备类似于 C 语言体系的行为。 —https://www.wendangku.net/doc/fb5980634.html, 2、JSON 的结构: (1) Name/Value Pairs 无序的):类 似所熟知的 Keyed list 、Hash table 、Disctionary 和 Associative array 。在Android 平台中同时存在另外一个类 "Bundle" ,某 种程度上具有相似的行为。 ⑵Array (有序的):一组 有序的数据列表。 对象对象是一个无序的 Name/Value Pairs 集合。 { name:value , name:value , name:value . }例子:

用jquery解析JSON数据的方法

用jquery解析JSON数据的方法 用jquery解析JSON数据的方法,作为jquery异步请求的传输对象,jquery请求后返回的结果是json对象,这里考虑的都是服务器返回JSON形式的字符串的形式,对于利用JSONObject等插件封装的JSON对象,与此亦是大同小异,这里不再做说明。这里首先给出JSON字符串集, 用jquery解析JSON数据的方法,作为jquery异步请求的传输对象,jquery 请求后返回的结果是json对象,这里考虑的都是服务器返回JSON 形式的字符串的形式,对于利用JSONObject等插件封装的JSON对象,与此亦是大同小异,这里不再做说明。 这里首先给出JSON字符串集,字符串集如下: 代码如下: var data=" { root: [ {name:'1',value:'0'}, {name:'6101',value:'北京市'}, {name:'6102',value:'天津市'}, {name:'6103',value:'上海市'}, {name:'6104',value:'重庆市'}, {name:'6105',value:'渭南市'}, {name:'6106',value:'延安市'}, {name:'6107',value:'汉中市'}, {name:'6108',value:'榆林市'}, {name:'6109',value:'安康市'}, {name:'6110',value:'商洛市'} ] }"; 这里以jquery异步获取的数据类型——json对象和字符串为依据,分别介绍两种方式获取到的结果处理方式。 1.对于服务器返回的JSON字符串,如果jquery异步请求没做类型说明,或者以字符串方式接受,那么需要做一次对象化处理,方式不是太麻烦,就是将该字符串放于eval()中执行一次。这种方式也适合以普通javascipt方式获取json对象,以下举例说明: var dataObj=eval("("+data+")");//转换为json对象 alert(dataObj.root.length);//输出root的子对象数量 $.each(dataObj.root,fucntion(idx,item){ if(idx==0){ return true; }

JS解析JSON数据及取值的用法

JS解析JSON数据及取值的一些用法 <%@ page contentType="text/html;charset=GBK" language="java" %> JS解析JSON数据

JS解析JSON数据测试界面

js解析json

JsJson js和json 工程地址: https://https://www.wendangku.net/doc/fb5980634.html,/svn/trunk/code/HtmlPro js解析json var json =eval(${json});//${json}:json字符串 格式 function test(){ var a = [//一个数组 {//一个json对象(类似于Bean,字段名:字段值) "省份":"福建", "面积":16800, "人口":1600, "城市":["福州","泉州","厦门","漳州"],//值可以是数组 "特产":{"吃":"海鲜","喝":"茶","玩":"武夷山"}//值可以是另一个json对象},{ "省份":"广东", "面积":6400, "人口":1800, "城市":["杭州","温州","台州","舟山"], "特产":{"吃":"海鲜","喝":"茶","玩":"西湖"} } ]; //调用属性两种;第一种:a[0]["省份"],第二种:a[0].省份 alert("省份:"+a[0]["省份"]+" 省份:"+a[0].省份+" 城市:"+a[0].城市[1]+" 特产.玩:"+a[0].特产.玩); var speciality = a[0].特产; var specialityName=""; //循环json里面的属性 for(var key in speciality){ specialityName = specialityName +" key: "+key+" value:"+speciality[key]; } alert("特产:"+specialityName);

JSON数据传输(详细解析)

JSON数据传输 一.什么是JSON 1.JSON是什么? JSON提供了一种更适合AJAX应用的标准数据交换格式。JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。 2.JSON数据格式是什么样的? 1.JSON是什么? JSON提供了一种更适合AJAX应用的标准数据交换格式。JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。 2.JSON数据格式是什么样的? 二.JS解析JSON格式数据 1. 客户端将json对象通过toJSONString(par)转换为字符串 2.解析JSON普通数据; 利用eval函数将返回的文本流转换成JS对象 A.知道属性名的; B.不知道属性名的。(For in) 3.解析JSON数组数据。 三.JA V A封装及解析JSON 1.通过String jsonString = request.getParameter(“jsonObject"); 获

取客户端json参数. 2.java怎么封装json格式数据 A.封装普通格式json数据; JSONObject returnObject=new JSONObject(); B.封装数组格式的json数据. 3.java解析json格式数据 JSONObject returnObject=new JSONObject(jsonString); String returnObject.getString(“属性名”); JSONArray jarr=returnObject.getJSONArray(“属性名”); 四.JSON格式数据传输的优缺点 1.优点 A.它们简化了数据访问,使用这些数据分隔符时,JavaScript引擎对数据结构(如字符串、数组、对象)的内部表示恰好与这些符号相同 B. JSON的另一个优点是它的非冗长性。在XML中,打开和关闭标记是必需的,这样才能满足标记的依从性;而在JSON中,所有这些要求只需通过一个简单的括号即可满足。在包含有数以百计字段的数据交换中,传统的XML标记将会延长数据交换时间。目前还没有正式的研究表明JSON比XML有更高的线上传输效率;人们只是通过简单的字节数比较发现,对于等效的JSON和XML有效负载,前者总是小于后者网上有人测试JSON的速度几乎是XML解析的10

JION数据格式详解

JSON 数据格式解析 和XML 一样,JSON 也是基于纯文本的数据格式。由于JSON 天生是为JavaScript 准备的,因此,JSON 的数据格式非常简单,您可以用JSON 传输一个简单的String,Number,Boolean,也可以传输一个数组,或者一个复杂的Object 对象。 String,Number 和Boolean 用JSON 表示非常简单。例如,用JSON 表示一个简单的String " abc ",其格式为:"abc",除了字符",\,/ 和一些控制符(\b,\f,\n,\r,\t)需要编码外,其他Unicode 字符可以直接输出。 Boolean 类型表示为true 或false 。此外,JavaScript 中的null 被表示为null,注意,true、false 和null 都没有双引号,否则将被视为一个String 。 JSON 还可以表示一个数组对象,使用[] 包含所有元素,每个元素用逗号分隔,元素可以是任意的Value,例如,以下数组包含了一个String,Number,Boolean 和一null:["abc",12345,false,null]

Object 对象在JSON 中是用{} 包含一系列无序的Key-Value 键值对表示的,实际上此处的Object 相当于Java 中的Map,而不是Java 的Class 。注意Key 只能用String 表示。例如,一个Address 对象包含如下Key-Value: city:Beijing street:Chaoyang Road postcode:100025(整数) 用JSON 表示如下:{"city":"Beijing","street":" Chaoyang Road ","postcode":100025}其中Value 也可以是另一个Object 或者数组,因此,复杂的Object 可以嵌套表示,例如,一个Person 对象包含name 和address 对象,可以表示如下:{"name":"Michael","address": {"city":"Beijing","street":" Chaoyang Road ","postcode":100025}} JavaScript 处理JSON 数据 上面介绍了如何用JSON 表示数据,接下来,我们还要解决如何在服务器端生成JSON 格式的数据以便发送到客户端,以及客户端如

jsoncpp详解

JSON详解 一、what is json JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,而Jsoncpp是个跨平台的开源库。 二、json的特性 JSON 数据的书写格式是:名称/值对。 名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:"firstName":"John"。 JSON 值可以是:数字(整数或浮点数)、字符串(在双引号中)、逻辑值(true 或 false)、数组(在方括号中)、对象(在花括号中)、null。对象在json中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构。数组在js中是中括号“[]”括起来的内容,数据结构为["java","javascript","vb",...]。 三、JsonCpp的基本语法 使用JsonCpp前先来熟悉几个主要的类: Json::Value 可以表示里所有的类型,比如int,string,object,array 等,具体应用将会在后边示例中介绍。 Json::Reader 将json文件流或字符串解析到Json::Value, 主要函数有Parse。 Json::Writer 与Json::Reader相反,将Json::Value转化成字符串流,注意它的两个子类:Json::FastWriter和Json::StyleWriter,分别输出不带格式的json和带格式的json。 1、Value Json::Value 是jsoncpp 中最基本、最重要的类,用于表示各种类型的对象,jsoncpp 支持的对象类型可见 Json::ValueType 枚举值。 可如下是用 Json::Value 类: Json::Value json_temp; json_temp["name"] = Json::Value("huchao");

JSON格式及读写讲解

JSON格式及读写讲解 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript (Standard ECMA-262 3rd Edition - December 1999)的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。 基础结构 JSON建构有两种结构:[1] json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组2种结构,通过这两种结构可以表示各种复杂的结构 1、对象:对象在js中表示为“{}”扩起来的内容,数据结构为{key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为对象.key 获取属性值,这个属性值的类型可以是数字、字符串、数组、对象几种。 2、数组:数组在js中是中括号“[]”扩起来的内容,数据结构为["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是数字、字符串、数组、对象几种。 经过对象、数组2种结构就可以组合成复杂的数据结构了。 基础示例 简单地说[1],JSON 可以将JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从Web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是JavaScript很容易解释它,而且JSON 可以表示比"名称/ 值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。 名称/ 值对 按照最简单的形式,可以用下面这样的JSON 表示"名称/ 值对":{ "firstName": "Brett" } 这个示例非常基本,而且实际上比等效的纯文本"名称/ 值对"占用更多的空间:firstName=Brett 但是,当将多个"名称/ 值对"串在一起时,JSON 就会体现出它的价值了。首先,可以创

JSON解析详细文档

JSON 的含义? JSON的全称是JavaScript Object Notation,是一种轻量级的数据交换格式。JS ON与XML具有相同的特性,例如易于人编写和阅读,易于机器生成和解析。但是JSON 比XML数据传输的有效性要高出很多。JSON完全独立与编程语言,使用文本格式保存。 JSON数据有两种结构: ?Name-Value 对构成的集合,类似于Java中的Map。 ?Value的有序列表,类似于Java中的Array。 一个JSON格式的数据示例: { "Name": "Apple", "Expiry": "2007/10/11 13:54", "Price": 3.99, "Sizes": [ "Small", "Medium", "Large" ] } 更多关于JSON数据格式的说明参看JSON官方网站:https://www.wendangku.net/doc/fb5980634.html,(中文内容参看:https://www.wendangku.net/doc/fb5980634.html,/json-zh.html) GWT与JSON GWT中支持的客户端服务器端方法调用和数据传递的标准格式是RPC。 JSON并不是GWT支持的标准的数据传递格式。那么如何使用JSON来作为GWT的数据传递格式呢?需要以下几步。 第一,引用HTTP和JSON支持。 第二,在客户端创建JSON数据,提交到服务器 第三,在服务器上重写数据格式解析的代码,使之支持JSON格式的数据 第四,在服务器上组织JSON格式的数据,返回给客户端。 第五,客户端解析服务器传回的JSON数据,正确的显示 引用HTTP和JSON支持

找到.gwt.xml文件,在其中的 在之后添加如下的内容: 其中com.google.gwt.json.JSON指的是要使用JSON,com.google.gwt.http.H TTP值得是通过HTTP调用服务器上的服务方法。 客户端构造JSON数据 客户端需要使用com.google.gwt.json.client包内的类来组装JSON格式的数据,数据格式如下: 数据类型说明 JSONArray JSONValue构成的数组类型 JSONBoolean JSON boolean值 访问JSON结构的数据出错的情况下可以抛出此异JSONException 常 JSONNull JSON Null根式的数据 JSONNumber JSON Number类型的数据 JSONObject JSON Object类型的数据 将String格式的JSON数据解析为JSONValue类JSONParser 型的数据 JSONString JSON String类型的数据 JSONValue 所有JSON类型值的超级类型组合一个简单的JSON数据:

标准JSON格式定义与解析注意点

JSON是一种轻量级的数据交换格式。它是基于javascript语法标准的一个子集。JSON是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,可以很容易在各种网络、平台和程序之间传输。JSON 的语法很简单,... JSON是一种轻量级的数据交换格式。它是基于javascript语法标准的一个子集。JSON 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,可以很容易在各种网络、平台和程序之间传输。JSON的语法很简单,易于人阅读和编写,同时也易于机器解析和生成。 要想熟练的操作json数据,就要先了解json数据: JSON的规则很简单:对象是一个无序的“…名称/值?对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“…名称/值?对”之间使用“,”(逗号)分隔。 规则如下: 1、映射用冒号(“:)表示。名称:值 2、并列的数据之间用逗号(“,”)分隔。名称1:值1,名称2:值2 3、映射的集合(对象)用大括号(“{}”)表示。 { 名称1:值1, 名称2:值2 } 4、并列数据的集合(数组)用方括号(“[]”)表示。 [ {名称1:值,名称2:值2}, {名称1:值,名称2:值2} ] 5、元素值可具有的类型:string,number, object, array, true, false, null 注意:1、JSON 用冒号(而不是等号)来赋值。每一条赋值语句用逗号分开。整个对象用大括号封装起来。可用大括号分级嵌套数据。

2、对象描述中存储的数据可以是字符串,数字或者布尔值。对象描述也可存储函数,那就是对象的方法。 6、JSON主要有两种数据结构 (1)由key–value对组成的数据结构。这种数据结构在不同的语言中有不同的实现. 例如:在javascript中是一个对象.而在java中是一种Map结构,c语言中是struct,其它的语言中可能为record、hash table 等。 (2)有序集合、这种数据结构在不同语言中可能有list、vertor、数组和序列等实现。 7、C#中json数据格式的处理 List转Json [csharp] public static string Obj2Json(T data) { try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); return Encoding.UTF8.GetString(ms.ToArray()); } } catch { return null; } } Json转List [csharp] public static Object Json2Obj(String json,Type t) { try {

相关文档