package cn.java.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class JsonTest {
@Test
public void stringToJson(){
int flag=1;
JSONObject json=new JSONObject("{flag:1}");
//String json="{‘flag’:1}";
System.out.println(json);
}
//将map集合转化为json
@Test
public void mapToJson(){
Map<String,Object> hm=new HashMap<String,Object>();
hm.put("username", "admin");
hm.put("password","123");
hm.put("gender","1");
JSONObject jsonObject=new JSONObject(hm);//这里的jsonObject是一个构造方法,立刻将hm转化为一个json
System.out.println(jsonObject.toString());
}
@Test
public void listToJson(){
Map<String,Object> hm1=new HashMap<String,Object>();
hm1.put("username", "admin");
hm1.put("password","123");
hm1.put("gender","1");
Map<String,Object> hm2=new HashMap<String,Object>();
hm2.put("username", "admin");
hm2.put("password","123");
hm2.put("gender","1");
List<Map<String,Object>> lists=new ArrayList<Map<String,Object>>();
lists.add(hm1);
lists.add(hm2);
JSONArray jsonArray=new JSONArray(lists);//如果将lists集合转化为json用jsonArray
System.out.println(jsonArray.toString());
}
}