首页 > Java > java教程 > 正文

Java 中的 JSON

WBOY
发布: 2024-08-30 16:02:12
原创
481 人浏览过

JavaScript 对象表示法(JavaScript Object Notation),在 Java 中也称为 JSON,是一种轻量级、基于文本、独立于语言、易于人类和机器读写的数据交换格式。这表示两种类型的结构,称为对象和数组,其中对象是没有或超过零的名称和值对的集合,并且是无序集合,而没有或超过零值的有序序列是数组。可能的值可以是数字、字符串、布尔值、null、对象和数组。

广告 该类别中的热门课程 JAVA 掌握 - 专业化 | 78 课程系列 | 15 次模拟测试

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

在 Java 中使用 JSON

  • 考虑下面的示例,用 JSON 表示一个对象来描述一个人。
  • 名字和姓氏取对象中字符串的值; Age 取对象中的数字值;地址采用字符串和数字的值来表示对象中人的地址;电话号码采用对象中数组的值。

代码:

{
"fName": "Shobha",
"lName": "Shivakumar",
"age1": 28,
"address1":
{
"streetAdd": "4, Ibbani street",
"city1": "Bangalore",
"state1": "Karnataka",
"pinCode": 560064
},
"phNumbers":
[
{
"type1": "home1",
"no": "9738128018"
},
{
"type2": "fax1",
"no1": "6366182095"
}
]
}
登录后复制
  • Java 中 JavaScript 对象表示法 (JSON) 的处理是通过使用 JavaScript 对象表示法的 Java 应用程序编程接口完成的,即 JSON.simple,JavaScript 对象表示法 JSON.simple 是 Java 中的一个库,允许解析 JavaScript 对象表示法、生成 JavaScript 对象表示法、转换 JavaScript 对象表示法、查询 JavaScript 对象表示法等
  • 为了使用 JavaScript 对象表示法简单库,在编译和运行 JavaScript 对象表示法编程示例之前,必须下载 json-simple-1.1.jar 并将其放入 CLASS PATH 中。
  • JavaScript 对象表示法对象和数组结构使用 JavaScript 对象表示法简单应用程序编程接口提供的对象模块。
  • 这些 JavaScript 对象表示法结构使用 JSON 对象和 JSON 数组类型来表示为对象模型。 JSON 对象提供了一个映射视图来访问模型中无名称和值对或超过零个名称和值对的集合。它是一个无序集合,JSON 数组提供了一个列表视图来访问模型中数组中无值或大于零值的有序序列。

Java 中的 JSON 示例

下面给出了 Java 中 JSON 的示例:

示例#1

Java 程序,用于演示 Java 中 JavaScript 对象表示法 (JSON) 的编码。

代码:

//Importing JSON simple library
import org.json.simple.JSONObject;
//Creating a public class
public class JsonEncode {
//Calling the main method
public static void main(String[] args) {
//Creating an object of JSON class
JSONObject obje = new JSONObject();
//Entering the values using the created object
obje.put("bal", new Double(100.22));
obje.put("number", new Integer(200));
obje.put("check_vvip", new Boolean(true));
obje.put("name1", "sean");
//Printing the values through the created object
System.out.print(obje);
}
}
登录后复制

在上面的示例中,创建了一个 JSON 对象 obje。使用 JSON 对象 object。双精度、整数、布尔值、字符串等值将作为输出打印。

输出:

Java 中的 JSON

示例#2

演示 JSON 对象和 JSON 数组使用的 Java 程序。

代码:

//importing JSON simple libraries
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
//creating a public class
public class JsonDecode{
//calling the main method
public static void main(String[] args) {
//creating an object of JSONparser
JSONParser par = new JSONParser();
//defining and assigning value to a string
String str = "[2,{\"3\":{\"4\":{\"5\":{\"6\":[7,{\"8\":9}]}}}}]";
try{
Object objc = par.parse(str);
//creating a JSON array
JSONArray array = (JSONArray)objc;
System.out.println("The array's second element is");
System.out.println(array.get(1));
System.out.println();
//creating a JSON object
JSONObject objc2 = (JSONObject)array.get(1);
System.out.println("Field \"2\"");
System.out.println(objc2.get("2"));
str = "{}";
objc = par.parse(str);
System.out.println(objc);
str = "[7,]";
objc = par.parse(str);
System.out.println(objc);
str = "[7,,2]";
objc = par.parse(str);
System.out.println(objc);
}catch(ParseException pr) {
System.out.println("The elements position is: " + pr.getPosition());
System.out.println(pr);
}
}
}
登录后复制

在上面的示例中,创建了 JSON 解析器 par 的 JSON 对象,然后定义并分配了一个字符串值。创建一个 JSON 数组来获取字符串中不同的指定元素。

输出:

Java 中的 JSON

示例 #3

使用 JavaScript 对象表示法对象和 JavaScript 对象表示法数组将 JavaScript 对象表示法数据写入名为 JSON.json 的文件的 Java 程序。

代码:

//importing java simple libraries and JSON libraries
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JSONWrite
{
public static void main(String[] args) throws FileNotFoundException
{
// Json object is created
JSONObject job = new JSONObject();
// Adding data using the created object
job.put("fName", "Shobha");
job.put("lName", "Shivakumar");
job.put("age1", 28);
// LinkedHashMap is created for address data
Map m1 = new LinkedHashMap(4);
m1.put("streetAdd", "4, Ibbani Street");
m1.put("city1", "Bangalore");
m1.put("state1", "Karnataka");
m1.put("pinCode", 560064);
// adding address to the created JSON object
job.put("address1", m1);
// JSONArray is created to add the phone numbers
JSONArray jab = new JSONArray();
m1 = new LinkedHashMap(2);
m1.put("type1", "home1");
m1.put("no", "9738128018");
// adding map to list
jab.add(m1);
m1 = new LinkedHashMap(2);
m1.put("type2", "fax1");
m1.put("no1", "6366182095");
// map is added to the list
jab.add(m1);
// adding phone numbers to the created JSON object
job.put("phoneNos", jab);
// the JSON data is written into the file
PrintWriter pwt = new PrintWriter("JSON.json");
pwt.write(job.toJSONString());
pwt.flush();
pwt.close();
}
}
登录后复制

在上面的示例中,创建了一个 JSON 对象作业。使用作业对象将名字、姓氏和年龄写入 JSON.json 文件。创建链接哈希映射以添加地址详细信息,然后使用 JSON 作业对象将其写入文件。创建 JSON 数组对象来添加电话号码,并使用链接的哈希映射来创建不同类型的电话号码;最后,使用 JSON 作业对象将这些电话号码写入文件。最终使用打印编写器将内容写入文件。

输出:

上述程序的输出是访问文件 JSON.json 以查看文件内容时的结果。

Note: Since JSON is an unordered collection of name or value pairs, there is no order preserved in the output shown below. Java 中的 JSON

Example #4

Java program to read the contents of the file JSON. JSON demonstrates the use of JavaScript Object Notation object parser, JavaScript Object Notation object, and JavaScript Object Notation object array.

Code:

//importing JSON simple libraries
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
public class JSONRead
{
public static void main(String[] args) throws Exception
{
// The file JSON.json is parsed
Object objc = new JSONParser().parse(new FileReader("JSON.json"));
// objc is convereted to JSON object
JSONObject job = (JSONObject) objc;
// obtaining the fname and lname
String fName = (String) job.get("fName");
String lName = (String) job.get("lName");
System.out.println(fName);
System.out.println(lName);
// age is obtained
long age1 = (long) job.get("age1");
System.out.println(age1);
// address is obtained
Map address1 = ((Map)job.get("address1"));
// iterating through the address
Iterator<Map.Entry> itr = address.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pair1 = itr1.next();
System.out.println(pair1.getKey() + " : " + pair1.getValue());
}
// phone numbers are obtained
JSONArray jab = (JSONArray) job.get("phoneNos");
// iterating phoneNumbers
Iterator itr1 = jab.iterator();
while (itr1.hasNext())
{
itr = ((Map) itr1.next()).entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pair1 = itr.next();
System.out.println(pair1.getKey() + " : " + pair1.getValue());
}
}
}
}
登录后复制

In the above example, the file JSON.json is parsed by creating an object objc which is then converted to a JSON object job. First name, last name, age, address, and phone numbers are read from the JSON.json file through iterations and printed as the output.

Output:

The output of the above program after reading the contents from the JSON.json file is shown in the snapshot below:

Java 中的 JSON

以上是Java 中的 JSON的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!