您的位置:首页 > Web前端 > JavaScript

JSON简单的代码实例

2018-03-24 11:52 281 查看

JSON简单代码基本实例:

本代码运行环境为eclipse的Maven项目下。


1.先简单介绍一下json

一种与开发语言无关的轻量级的数据格式。优点:易读和编写,易于程序解析与生产

2.标准的json数据表示

<1>数据结构

object:

使用花括号包含的键值对结构,key必须是string类型,

value可以为任何基本类型或数据结构

Array:

使用中括号[]来起始,并用逗号,来分隔元素;

<2>数据类型

String

number

true/false

null

代码块

json文件示例:

json文件:
{
"name":"王小二",
"age":25.2,
"birthday":"1990-01-01",
"school":"蓝翔",
"major(技能)":["理发","挖掘机"],
"has_girlfriend":false,
"car":null,
"house":null,
"comment":"这是一个注释"
}


生成json数据的三种方式

方法具体操作
JSONObject对象通过对象.方法,以键值对的形式传入参数(对象.put(key,value);)。
Map集合Map集合对象的数据本身为key-value。将Map对象传入JSONObject.fromObject()方法中。
javabean方法通过创建好的类(封装),用get-set方法实现。最终将类的对象传入JSONObject.fromObject()方法

代码块

json文件的解析:

package Json.json;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
*
* 解析json数据。
* */

public class ReadJSONSample {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = JSONObject.fromObject(content);
if (jsonObject.containsKey("name")) {
System.out.println("姓名是:"+jsonObject.getString("name"));
}
if(jsonObject.containsKey("nickname")) {
System.out.println("姓名是:"+jsonObject.getString("nickname"));
}
//System.out.println("姓名是:"+jsonObject.getString("name"));
System.out.println("年龄:"+jsonObject.getDouble("age"));
System.out.println("有没有女朋友:"+jsonObject.getBoolean("has_girlfriend"));
JSONArray majorArray = jsonObject.getJSONArray("major");
Iterator<?> iterator = majorArray.iterator();
int i = 0;
if (iterator.hasNext()) {
System.out.println((String)majorArray.get(i));
i++;
}
}
}


.

JSON与GSON

GSON同样也可以生成json数据。具体的代码操作为(wangxiaoer为json数据的实例),

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(wangxiaoedr))


以上就为JSON最基本的操作与用服务于javaweb项目前端与后台之间的数据传输。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JSON最基本