JSON總結(java篇)


JSON總結(java篇一)

JSON簡介

JSON(JavaScript Object Notation)
是一種輕量級的數據交換格式。它基於ECMAScript的一個子集。 JSON采用完全獨立於語言的文本格式,但是也使用了類似於C語言家族的習慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。這些特性使JSON成為理想的數據交換語言。 易於人閱讀和編寫,同時也易於機器解析和生成(一般用於提升網絡傳輸速率)。

JSON語法

  • 數據在鍵值對中
  • 數據由逗號分隔
  • 花括號保存對象
  • 方括號保存數組

JSON值類型

  • number(整數或浮點數)
  • String(字符串,在雙引號中)
  • boolean(布爾值,true或false)
  • array(數組,用方括號表示)
  • Object(對象,在花括號中,例如javaScript對象)
  • null

java中的用法

准備工作

  1. 在java中使用json的方法首先要導入第三方jar包,進入json主頁http://json.org,然后下載java第三方包,這里我們使用JSON-java這個包。
    點擊后進入github下載頁面下載jar包。
  2. 這里我使用的是maven項目,所以可以在http://maven.org中搜索JSON-java的坐標。
  3. 在eclipse中創建maven項目,配置好pom.xml

JSON的使用

1. 使用Map集合創建JSON

    /**
	 * 1 、使用Map創建json
	 */
	public static void createJSONByMap() {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("name", "老王");
		map.put("age", 35);
		map.put("height", 1.73);
		map.put("major", new String[] { "理發", "挖掘機" });
		map.put("hasGirlFriend", false);
		map.put("car", null);
		JSONObject json = new JSONObject(map);
		System.out.println("方法名:createJSONByMap()---" + json);
	}

運行結果:

方法名:createJSONByMap()---{"major":["理發","挖掘機"],"name":"老王","hasGirlFriend":false,"age":35,"height":1.73}

從結果可以看出,car的字段沒有打印出來,說明當value為null時轉換JSON后不會顯示出來

2. 使用javaBean創建JSON

javaBean

package com.hjw.maven.jsonTest;

import java.util.Arrays;

/**
 *@author hjw
 *@version 創建時間:2016年9月21日 上午11:23:51
 * TODO
 */
public class Person {
	
	private String name;
	private int age;
	private double height;
	private String[] major;
	private boolean hasGirlFriend;
	
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public String[] getMajor() {
		return major;
	}
	public void setMajor(String[] major) {
		this.major = major;
	}
	public boolean isHasGirlFriend() {
		return hasGirlFriend;
	}
	public void setHasGirlFriend(boolean hasGirlFriend) {
		this.hasGirlFriend = hasGirlFriend;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", height=" + height
				+ ", major=" + Arrays.toString(major) + ", hasGirlFriend="
				+ hasGirlFriend + "]";
	}
	
	

}

    /**
	 * 2、通過javaBean創建json
	 */
	public static void createJSONByBean() {
		Person person = new Person();
		person.setName("老王");
		person.setAge(35);
		person.setHasGirlFriend(false);
		person.setHeight(17.2);
		person.setMajor(new String[] { "廚師", "編程" });
		System.out.println("方法名:createJSONByBean()---" + new JSONObject(person));

	}

方法名:createJSONByBean()---{"major":["廚師","編程"],"name":"老王","hasGirlFriend":false,"age":35,"height":17.2}

3. 通過JSONObject創建JSON

    /**
	 * 1、通過JSONObject來專家json
	 */
	public static void createJSON() {
		JSONObject json = new JSONObject();
		Object objNull = null;
		json.put("name", "老王");
		json.put("age", 35);
		json.put("height", 1.73);
		json.put("major", new String[] { "理發", "挖掘機" });
		json.put("hasGrilFriend", false);
		System.out.println("方法名:createJSON1()---" + json);
	}

方法名:createJSON()---{"hasGrilFriend":false,"major":["理發","挖掘機"],"name":"老王","age":35,"height":1.73}

4. 讀取文件創建JSONObject

在maven項目src/main/resource中創建laowang.json文件,然后引入commons-io的maven坐標

laowang.json
{
    "hasGrilFriend": false,
    "major": [
        "理發",
        "挖掘機"
    ],
    "name": "老王",
    "age": 35,
    "height": 1.73
}

代碼:

    /**
	 * 4、讀取文件獲取json
	 * 
	 * @throws IOException
	 */
	public static void createJsonByFile() throws IOException {
		File file = new File(JsonDemo.class.getResource("/laowang.json")
				.getFile());
		String content = FileUtils.readFileToString(file);
		JSONObject json = new JSONObject(content);
		System.out.println("name=" + json.getString("name"));
		System.out.println("age=" + json.getInt("age"));
		System.out.println("height=" + json.getDouble("height"));
		System.out.println("hasGirlFriend=" + json.getBoolean("hasGirlFriend"));
		System.out.print("major=[");
		for (Object str : json.getJSONArray("major")) {
			System.out.print(str + ",");
		}
		System.out.println("]");
	}

運行結果:

name=老王
age=35
height=1.73
hasGirlFriend=false
major=[理發,挖掘機,]

5. 通過JSONObject創建json文件

    /**
	 * 創建josn文件
	 * 
	 * @throws IOException
	 */
	public static void createJsonFileByWriter() throws IOException {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("name", "老王");
		map.put("age", 35);
		map.put("height", 1.73);
		map.put("major", new String[] { "理發", "挖掘機" });
		map.put("hasGrilFriend", false);
		JSONObject json = new JSONObject(map);
		URL url=JsonDemo.class.getResource("/");
		String path=url.getPath();
		path=path.substring(0, path.indexOf("jsonTest"));
		File file = new File(path+"/jsonTest/src/main/resource/laowang1.json");
		if (!file.exists()) {
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);
		json.write(bw);
		bw.close();
		System.out.println("end");
	}

代碼運行后會自動在maven項目中的resource路徑下生產一個名為laowang1.json的文件,其中jsonTest為項目名


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM