一
将map转为json
新建一个map
Map<String, String> map = new HashMap<String, String>();
map.put("1","1");
map.put("2","2");
使用JSONObject就可以将map直接转为json
package test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
demo1();
}
public static void demo1() {
//map->json
Map<String, String> map = new HashMap<String, String>();
map.put("1","1");
map.put("2","2");
JSONObject json = new JSONObject(map);
System.out.println(json);
//{"1":"1","2":"2"}
//json格式
}
}
输出结果为{"1":"1","2":"2"}
二
将对象转为json
直接使用JSONObject 来将对象转为json格式:JSONObject json = new JSONObject(entity);
新建一个对象
package dao;
public class Entity {
String name;
int age;
Address address;
public Entity() {
}
public Entity(String name, int age, Address address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
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;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "name" + " " + name + " " + "age";
}
}
package dao;
public class Address {
String a1;
String a2;
public Address() {
}
public Address(String a1, String a2) {
super();
this.a1 = a1;
this.a2 = a2;
}
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
public String getA2() {
return a2;
}
public void setA2(String a2) {
this.a2 = a2;
}
}
package test;
import org.json.JSONObject;
import dao.Address;
import dao.Entity;
public class Test {
public static void main(String[] args) throws IOException {
demo2();
}
public static void demo2() {
//javaBean->json
Entity entity = new Entity();
Address address = new Address("a1","a2");
entity.setAddress(address);
entity.setAge(15);
entity.setName("s");
JSONObject json = new JSONObject(entity);
System.out.println(json);
//{"address":{"a1":"a1","a2":"a2"},"name":"s","age":15}
}
}
三
将字符串转为json
在字符串中要写成键值对的形式,如果是字符串要有转义字符
String str = "{\"name\":\"zs\",\"age\":23}";
package test;
import org.json.JSONObject;
public class Test {
public static void main(String[] args){
demo3();
}
public static void demo3() {
String str = "{\"name\":\"zs\",\"age\":23}";
JSONObject json = new JSONObject(str);
System.out.println(str);
//{"name":"zs","age":23}
}
}