• 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为项目名

  • 相关阅读:
    c# datagridview 设置某行不可见解决办法
    MessageBox, MessageBoxBurttons, MessageBoxIcon 详细解析
    c# 项目带皮肤一起打包发布解决办法
    Winform DataGridView CheckBoxColumn c# 单选 解决方案
    机器学习 课程笔记
    机器学习-review-1 线性回归
    Office升级到2013版后无法登录微软账号问题
    Address already in use: make_sock: could not bind to address 0.0.0.0:80
    PHP的数组排序函数
    事件与委托例子
  • 原文地址:https://www.cnblogs.com/gongchenglion/p/5892967.html
Copyright © 2020-2023  润新知