一、什麼是JSON
JSON是一種輕量級的資料交換格式,採用完全獨立於程式語言的文字格式來儲存和表示資料。簡潔和清晰的層次結構使得 JSON 成為理想的資料交換語言。易於閱讀和編寫,同時也易於解析和生成,並有效地提升網路傳輸效率。
二、JSON 語法
(1)資料在名稱/值對中
(2)資料以逗號分隔
#(3)大括號保存物件 (4)中括號保存陣列三、Java中JSON的產生與解析的四種方式(簡單的Demo):一個實體類別:用於與JSON資料進行相互轉換
public class Person { private String name; private String sex; private int age; public Person(String name, String sex, int age) { this.name = name; this.sex = sex; this.age = age; } public String getName() { return name; } public String getSex() { return sex; } public int getAge() { return age; } @Override public String toString() { return "Person{name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + '}'; } }
public Person getPerson(){ return new Person("张三", "男", 25); } @Test public void EntityToJson(){ JSONObject jsonObject = new JSONObject(); jsonObject.put("name", getPerson().getName()); jsonObject.put("sex", getPerson().getSex()); jsonObject.put("age", getPerson().getAge()); System.out.println(jsonObject.toString()); }
@Test public void JsonToEntity(){ String jsonString = "{\"sex\":\"男\",\"name\":\"张三\",\"age\":25}"; JSONObject jsonObject = new JSONObject(jsonString); Person person = new Person(jsonObject.get("name").toString(), jsonObject.get("sex").toString(), Integer.valueOf(jsonObject.get("age").toString())); System.out.println(person.toString()); }
@Test public void EntityToJson() throws IOException { Person person = new Person("张三", "男", 25); ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(person); System.out.println(jsonString); }
@Test public void JsonToEntity() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"张三\",\"sex\":\"男\",\"age\":25}"; Person person = objectMapper.readValue(jsonString, Person.class); System.out.println(person); }
@Test public void EntityToJson(){ Person person = new Person("张三", "男", 25); Gson gson = new Gson(); String jsonString = gson.toJson(person); System.out.println(jsonString); }
@Test public void JsonToEntity(){ String jsonString = "{\"name\":\"张三\",\"sex\":\"男\",\"age\":25}"; Gson gson = new Gson(); Person person = gson.fromJson(jsonString, Person.class); System.out.println(person.toString()); }
@Test public void EntityToJson(){ Person person = new Person("张三", "男", 25); Object jsonString = JSON.toJSON(person); System.out.println(jsonString.toString()); }
@Test public void JsonToEntity(){ String jsonString = "{\"name\":\"张三\",\"sex\":\"男\",\"age\":25}"; Person person = JSON.parseObject(jsonString, Person.class); System.out.println(person.toString()); }
以上是JAVA的json怎麼解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!