1. 构建JSON方法(数据——>JSON)

这里使用Maven构建项目

在pom.xml中添加如下依赖

 <dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>

1.1 创建JSONObject对象,利用put(key,value)赋值,toString() 打印出JSON格式

关键词:JSONObject对象,put(), toString()

public class JsonObjectSimple {

    public static void main(String[] args) {
jSONObjectSimple();
} private static void jSONObjectSimple() { JSONObject xiaofeng=new JSONObject();
Object nullObj=null;//因为put()方法的原因,这里不能直接使用null,所以创建null的对象来跳过编译器的检查
try {
xiaofeng.put("name", "小峰");
xiaofeng.put("age", 22);
xiaofeng.put("birthday", "1999-11-22");
xiaofeng.put("school", "Qinghua University");
xiaofeng.put("major", new String[] {"sing","coding"});
xiaofeng.put("girlfriend", "true");
xiaofeng.put("car",nullObj); //不能直接使用null,需要创建null的对象来跳过编译器的检查
xiaofeng.put("comment","JSON里不能直接使用注释,需要添加时可通过此方式。。"); } catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(xiaofeng.toString());
}
}

控制台输出后复制其到 http://www.jsoneditoronline.org/ 可查看 JSON 数据结构

1.2 通过 HashMap 构建

关键词:HashMap() , put() , toString() , JSONObject(xiaofeng)

private static void createJSONByMap() {

        Map<String,Object> xiaofeng=new HashMap<String,Object>();
Object nullObj=null;
xiaofeng.put("name", "小峰");
xiaofeng.put("age", 22);
xiaofeng.put("birthday", "1999-11-22");
xiaofeng.put("school", "Qinghua University");
xiaofeng.put("major", new String[] {"sing","coding"});
xiaofeng.put("girlfriend", "true");
xiaofeng.put("car",nullObj); //不能直接使用null,需要创建null的对象来跳过编译器的检查
xiaofeng.put("comment","JSON里不能直接使用注释,需要添加时可通过此方式。。"); System.out.println(new JSONObject(xiaofeng).toString());
}

3. 使用 JavaBean 创建 JSON

关键词:JavaBean,  setXxx(),  JSONObject(xiaofeng)

首先创建 JavaBean 类Person(略),  之后创建。。。

private static void createJSONByBean() {
//创建Person对象,利用set()方法赋值,最后转为JSONObject对象输出
Person xiaofeng=new Person();
xiaofeng.setName("小峰");
xiaofeng.setAge(22.5);
xiaofeng.setGirlfriend(true);
xiaofeng.setMajor(new String[]{"唱歌","coding"}); System.out.println(new JSONObject(xiaofeng));
}

注意,在创建JavaBean时,由于JSON不支持date格式,所以日期格式需要设置为String类型,这也是JSON的缺陷。

2. 解析读取JSON数据(JSON——>数据)

xiaofeng.json
{
"birthday": "1999-11-22",
"girlfriend": "true",
"major": [
"sing",
"coding"
],
"school": "Qinghua University",
"car": null,
"name": "小峰",
"comment": "JSON里不能直接使用注释,需要添加时可通过此方式。。",
"age": 22
}

从文件中读取JSON

关键词:

ReadJSON.class.getResource("/xiaofeng.json").getFile() ,JSONArray,readFileToString(file)

public class ReadJSON {

    public static void main(String[] args) throws IOException, JSONException {
//获取本文件路径下的json文件
File file=new File(ReadJSON.class.getResource("/xiaofeng.json").getFile());
//读取json文件内容
String content=FileUtils.readFileToString(file);
JSONObject jsonObject =new JSONObject(content);
System.out.println("姓名是 :"+jsonObject.getString("name"));
System.out.println("年龄是 :"+jsonObject.getDouble("age"));
System.out.println("有女朋友吗 ?"+jsonObject.getBoolean("girlfriend"));

//数组类型转换成JSONArray类型来解析,不能直接读取
JSONArray majorArray=jsonObject.getJSONArray("major");
for(int i=0;i<majorArray.length();i++){
String m=(String) majorArray.get(i);
System.out.println("专业——"+(i+1)+m);
}
} }

控制台输出

              

为增加程序健壮性,可在JSON数据解析时加入 非空【isNull()】 判断

     //判断 name 是否为空
if (!jsonObject.isNull("name")) {
System.out.println("姓名是 :" + jsonObject.getString("name"));
}
//反例,无输出
if (!jsonObject.isNull("nme")) {
System.out.println("姓名是 :" + jsonObject.getString("name"));
} System.out.println("年龄是 :" + jsonObject.getDouble("age"));

JSON——Java中的使用的更多相关文章

  1. json:java中前台向后台传对象数据

    前台传入的是一个json类型的数据,如何在后台解析成想要的数据类型? 例如: 后台获取了前台一个string类型的数据@RequestParam(value = "forceUpgradeT ...

  2. Java中json的构造和解析

    什么是 Json? JSON(JvaScript Object Notation)(官网网站:http://www.json.org/)是 一种轻量级的数据交换格式.  易于人阅读和编写.同时也易于机 ...

  3. JAVA中使用JSON进行数据传递

    最近在做一个基于JAVA Servlet的WEB应用以及对应的Anroid应用客户端的开发工作. 其中,在接口的访问和数据的传输方面使用的比较多的是使用JSON对象来操作格式化数据:在服务器端采用JS ...

  4. Java中JSON的简单使用与前端解析

    http://www.blogjava.net/qileilove/archive/2014/06/13/414694.html 一.JSON JSON(JavaScript Object Notat ...

  5. Java中json工具对比分析

    Java中几个json工具分析 1, 环境 JDK1.6+IDE(IntelliJ IDEA)+windowsXP+GBK编码 2,分析对象 jackson1.8.2 http://jackson.c ...

  6. 在java代码中显示json字符串(怎么避免json字符串中双引号在java代码中显示)

    String log = "eyJvcmRlckluZm8iOnsiaWQiOjEwNzQwNCwib3JkZXJJZCI6MjczNjQyMSwicHJvZHVjdENvZGUiOjQ1N ...

  7. JAVA中,JSON MAP LIST的相互转换

    1 JSON包含对象和数组,对应于JAVA中的JSONObject,JSONArray 2 String 转JSON对象 JSONObject.fromObject("String" ...

  8. 转载:JAVA中使用JSON进行数据传递

    转载网址:http://www.cnblogs.com/undead/archive/2012/07/18/2594900.html 最近在做一个基于JAVA Servlet的WEB应用以及对应的An ...

  9. java 中关于json的使用方法

    json在数据传输起了很大的作用,下面说说java中json的使用方法. 文章参考:http://www.codes51.com/article/detail_99574.html json串示例 [ ...

随机推荐

  1. php使用memcached详解

    一.memcached 简介 在很多场合,我们都会听到 memcached 这个名字,但很多同学只是听过,并没有用过或实际了解过,只知道它是一个很不错的东东.这里简单介绍一下,memcached 是高 ...

  2. 在ubuntu下面为php添加redis扩展

    首先下载redis扩展:wget https://github.com/nicolasff/phpredis/zipball/master -o php-redis.zip 解压缩:unzip php ...

  3. codeforces734E

    题目连接:http://codeforces.com/contest/734/problem/E E. Anton and Tree time limit per test 3 seconds mem ...

  4. Lock wait timeout exceeded数据库死锁问题

    环境 MySQL5.5 现象 A.数据更新或新增后数据经常自动回滚. B.表操作总报 Lock wait timeout exceeded 并长时间无反应 解决方法 A.应急方法:show proce ...

  5. Naming conventions of python

    1.package name 全部小写字母,中间可以由点分隔开,作为命名空间,包名应该具有唯一性,推荐采用公司或组织域名的倒置,如com.apple.quicktime.v2 2.module nam ...

  6. sqlplus terminators - Semicolumn (;), slash (/) and a blank line

    The problem here is the way SQL*Plus interprets the commands passed to it. Remember the "SQL co ...

  7. 中文名: 交通事故责任认定, 英文名称: Traffic accident responsibility identification

    中文名: 交通事故责任认定, 英文名称: Traffic accident responsibility identification

  8. 【CCpp程序设计2017】迷宫游戏

    大一寒假作业!写了第一个小游戏! //maze_test By lizitong #include<stdio.h> #include<time.h> #include< ...

  9. 【数位dp】hdu2089 不要62

    http://www.cnblogs.com/xiaohongmao/p/3473599.html #include<cstdio> using namespace std; int n, ...

  10. Problem H: 零起点学算法28——参加程序设计竞赛

    #include<stdio.h> int main() { int a,b; while(scanf("%d %d",&a,&b)!=EOF) ||b ...