作业解析-Java JSON Object Equality

目录

1. 作业题目

2. 作业目的

3. 运行效果

4. 实现过程

5. 知识点巩固

6 知识拓展

7 学习建议

作业辅导解析

JSON Object Equality 9th Feb,2019

1.作业题目:

QuestionDetermining if two JSON objects are equal is a common and useful operation. Two JSON objects are equal if they have the same set of key-value pairs (not necessarily in the same order), where for each key, the values are equal. In the case of primitive values such as strings, numbers, true, false, and null, two values are equal if they are the same. In the case of arrays, two arrays are equal if both arrays have the same number of elements and they are pairwise equal. I.e., for each array element, the values stored in both arrays are equal For example, the following two figures are examples of equal and unequal objects. Write a program called JSim.java that reads in two JSON objects from the console and determines if they are the equal. Your JSim.java program must contain the main() method where your program starts running.

2.作业目的:

1、 掌握 Java 语言递归的应用 2、 掌握 Java list stack 等数据结构 3、 提高编程能力

3.运行效果:

image

4.实现过程:

image

参考源码图 1.1

核心代码上图所示,本次作业主要通过以下步骤实现:

1、 初始化 JSONScanner,接收输入文本 2、 编写递归解析函数,解析输入文本为 JSONObject 并存储到 TreeMap 3、 判断两个 JSON 是否键值对成对相等 4、 编写 Map 转标准 JSON 格式输出打印递归函数,根据 3 中的判断结果,按字母序打印 输 JSON 到控制台

5.知识点巩固:

-JSON

JSON,(JavaScript Object Notation)是一种广泛使用的编码格式,可以轻松交换数据。 JSON 是一种基于文本(人类可读)的格式,使其成为许多应用程序的理想选择,并且易于 调试。JSON 使用对象,数组和原始值对数据进行编码。JSON 对象被编码为零个或多个键 值对,其中键是字符串,值可以是对象,数组,字符串,数字,truefalse null。字符串 是用双引号括起来的任何文本,例如“Hello World”,数字是整数或十进制值,例如 42 3.14。 对象以左括号({)开头,包含零个或多个键值对,以右大括号(}结束,

image

1-2

6.知识拓展:

-TreeMap

TreeMap 是一个有序的 key-value 集合,它是通过红黑树实现的。

TreeMap 继承于 AbstractMap,所以它是一个 Map,即一个 key-value 集合。该映射根据 其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决 于使用的构造方法。TreeMap 的基本操作 containsKeygetput remove 的时间复杂 度是 log(n)

-Break Label

标号提供了一种简单的 break 语句所不能实现的控制循环的方法,当在循环语句中遇到 break 时,不管其它控制变量,都会终止。但是,当你嵌套在几层循环中想退出循环时又会 怎样呢?正常的 break 只退出一重循环,你可以用标号标出你想退出哪一个语句。

char a;

outer: //this is the label for the outer loop for(int i=0;i<10;i++){

for(int j=0;j<10;j++){ a=(char)System.in.read(); if(a==’b’) break outer; if(a==’c’) continue outer;

}

}

在这个例子中,循环从键盘接受 100 个输入字符,输入“b”字符时,break outer 语句会结束 两重循环,注意 continue outer 语句,它告诉计算机退出现在的循环并继续执行 outer 循环

7.学习建议:

1JSON 解析、转换等操作是非常实用且常用的,现在有非常多优秀的开源 JSON 解析工 具可供使用和学习,比如 Gson 2、 编写递归代码时可能不太容易一次写对,多 debug