java写的JSON例子:
package com.yiheng.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.springframework.core.ReactiveAdapterRegistry;
import java.util.*;
public class DemoObject {
//JSON添加对象
@Test
public void addObject() {
String band = "{'brand':'huawei','color':'blue'}";
JSonObject band1 = JSON.parseObject(band);
band1.put("price", 700);
System.out.println(band1);
System.out.println(band1.getString("brand"));
System.out.println(band1.getInteger("price"));
}
//JSONObject
@Test
public void printObj(){
String stu_str="{'no':'001','name':'张三','score':{'chinese':90,'math':'90'}}";
JSonObject stu_obj = JSON.parseObject(stu_str);
JSonObject score = stu_obj.getJSONObject("score");
System.out.println(score.getInteger("chinese"));
System.out.println(score.getString("math"));
}
//JSONArray
@Test
public void printArr(){
String class_str="{'cname':'高一三班','student':[{'no':'001','name':'yiheng'},{'on':'002','name':'哇哈哈'}]}";
JSonObject class_obj = JSON.parseObject(class_str);
String student = class_obj.getString("student");
JSonArray student_arr = JSON.parseArray(student);
System.out.println(student_arr);
for(int i=0;i map = new HashMap<>();
map.put("name","yiheng");
map.put("sex","man");
map.put("age","22");
Iterator> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry node=iterator.next();
System.out.println(node.getKey()+":"+node.getValue());
}
}
//访问LIst
@Test
public void DemoList(){
List list = new ArrayList<>();
for(int i=0;i<3;i++) {
list.add("list" + i);
}
//方法一
System.out.println("List访问方法一");
for(int i=0;i ite=list.iterator();
while (ite.hasNext())
{
System.out.println(ite.next());
}
//方法三
System.out.println("list访问方法三");
for(String node:list){
System.out.println(node);
}
}
}