이 기사는 Java를 기반으로 JSON을 구문 분석하는 세 가지 방법을 분석합니다. 다음과 같이 참조에 대해 공유하십시오.
1. JSON이란 무엇입니까?
JSON은 XML을 대체하는 데이터 구조입니다. XML과 비교하여 작지만 설명 기능이 양호합니다. 작기 때문에 네트워크는 데이터를 전송하여 더 많은 트래픽을 줄이고 속도를 높입니다.
JSON은 일련의 문자열이지만 요소는 특정 기호로 표시됩니다.
{} 이중 괄호는 물체를 나타냅니다
[] 브래킷은 어레이를 나타냅니다
""이중 인용문은 속성 또는 값입니다
: 콜론은 후자가 전자의 값임을 나타냅니다 (이 값은 문자열, 숫자 또는 다른 배열 또는 객체 일 수 있음)
{ "name": "michael"}}은 Michael과 같은 이름을 포함하는 객체로 이해 될 수 있습니다.
그리고 [{ "name": "michael"}, { "name": "jerry"}]는 두 개의 객체를 포함하는 배열을 의미합니다.
물론 { "name": [ "michael", "jerry"]}를 사용하여 위의 이름을 단순화 할 수도 있습니다.
2. 전통적인 JSON 분석 : JSON 분석
1. JSON 문자열을 생성합니다
public static string createjsongring (문자열 키, 개체 값) {jsonobject jsonobject = new JsonObject (); jsonobject.put (키, 값); return jsonobject.tostring ();}2. Parsing JSON 현
Javabean, 목록 배열 및 중첩 된 맵이있는 목록 배열의 다음 세 가지 상황으로 나뉩니다.
import java.util.arraylist; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; import org.json.jsonarray; import org.json.json.json.jsonobject; import com.android.myjson.domain.person;/***/**/***/***/*/*/*/*/*/*/*/*/*/** json.json.json.json.jsonarray; JSONTOOLS {public static person getperson (문자열 키, 문자열 JSonstring) {person perient = new person (); try {jsonobject jsonobject = new jsonobject (jsonstring); jsonObject personObject = jsonObject.getJsonObject ( "person"); person.setid (personobject.getint ( "id")); person.setName (personObject.getString ( "name")); person.setAddress (personObject.getString ( "주소")); } catch (예외 e) {// todo : handle exception} return person; } public static list getPersons (문자열 키, 문자열 jsonstring) {list list = new arrayList (); try {jsonobject jsonobject = new jsonobject (jsonstring); // jsonarray jsonarray = jsonobject.getJsonArray (key)의 배열을 반환합니다. for (int i = 0; i <jsonarray.length (); i ++) {jsonobject jsonobject2 = jsonarray.getjsonobject (i); 사람 = 새로운 사람 (); person.setid (jsonobject2.getint ( "id")); person.setname (jsonobject2.getstring ( "name")); person.setAddress (jsonobject2.getString ( "주소")); list.add (사람); }} catch (예외 e) {// todo : handle exception} 리턴 목록; } public static list getList (문자열 키, 문자열 jsonstring) {list list = new arrayList (); try {jsonobject jsonobject = new jsonobject (jsonstring); jsonarray jsonarray = jsonobject.getJsonArray (키); for (int i = 0; i <jsonarray.length (); i ++) {string msg = jsonarray.getstring (i); list.add (msg); }} catch (예외 e) {// todo : handle exception} 리턴 목록; } public static list> listKeymaps (문자열 키, 문자열 jsonstring) {list> list = new arraylist> (); try {jsonobject jsonobject = new jsonobject (jsonstring); jsonarray jsonarray = jsonobject.getJsonArray (키); for (int i = 0; i <jsonarray.length (); i ++) {jsonobject jsonobject2 = jsonarray.getjsonobject (i); 지도 맵 = new Hashmap (); 반복자 iterator = jsonobject2.keys (); while (iterator.hasnext ()) {String json_key = iterator.next (); 개체 json_value = jsonobject2.get (json_key); if (json_value == null) {json_value = ""; } map.put (json_key, json_value); } list.add (지도); }} catch (예외 e) {// todo : handle exception} 리턴 목록; }}3. JSON의 GSON 분석
1. JSON 문자열을 생성합니다
import com.google.gson.gson; public class jsonutils {public static string createjsonobject (object obj) {gson gson = new Gson (); 문자열 str = gson.tojson (obj); Return str; }}2. JSON을 분석하십시오
import java.util.arraylist; import java.util.list; import java.util.map; import com.google.gson.gson; import com.google.gson.reflect.typetoken ;; public class gsontools {public gsontools () {// a auto-generated stub} / * @param am * @@param am * @param am ** @param am ** @param a a a auto-generated stub}. @param cls * @return */ public static t getperson (String Jsonstring, 클래스 cls) {t t = null; try {gson gson = new Gson (); t = gson.fromjson (Jsonstring, CLS); } catch (예외 e) {// todo : handle exception} return t; } / ** * GSON을 사용하여 목록을 구문 분석하십시오 * * @param * @param Jsonstring * @param cls * @return * / public static list getpersons (String Jsonstring, 클래스 cls) {list list = new arraylist (); try {gson gson = new Gson (); list = gson.fromjson (jsonstring, new typetoken> () {} .getType ()); } catch (예외 e) {} 리턴 목록; } / ** * @param jsonstring * @return * / public static list getList (String JSonstring) {list list = new arrayList (); try {gson gson = new Gson (); list = gson.fromjson (jsonstring, new typetoken> () {} .getType ()); } catch (예외 e) {// todo : 핸들 예외} 리턴 목록; } public static list> listKeymaps (String jsonstring) {list> list = new ArrayList> (); try {gson gson = new Gson (); list = gson.fromjson (jsonstring, new typetoken >> () {} .getType ()); } catch (예외 e) {// todo : 핸들 예외} 리턴 목록; }}4. Fastjson 파싱
import java.util.arraylist; import java.util.list; import java.util.map; import com.alibaba.fastjson.json; import com.alibaba.fastjson.typereference; public static t getperson (문자열 jsonstring, class cls) {t = null; try {t = json.parseobject (jsonstring, cls); } catch (예외 e) {// todo : handle exception} return t; } public static list getPersonList (String JSonstring, 클래스 CLS) {list list = new ArrayList (); try {list = json.parsearray (jsonstring, cls); } catch (예외 e) {// todo : 핸들 예외} 리턴 목록; } public static list> getPersonListMap1 (String JSonstring) {list> list = new ArrayList> (); try {list = json.parseobject (jsonstring, new typereference >> () {} .getType ()); } catch (예외 e) {// todo : 핸들 예외} 리턴 목록; }}요약 :
모바일 장치의 경우, 특히 네트워크 환경 및 트래픽 제한이 열악한 경우 JSON은 트래픽을 절약하고 XML 형식 데이터 전송에 비해 전송 효율이 높아집니다. 이 세 가지 분석 방법 중에서 Fastjson이 가장 효율적이며 권장됩니다.
추신 : JSON 운영과 관련하여 참조를위한 실용적인 JSON 온라인 도구는 다음과 같습니다. 온라인 JSON 코드 검증, 검사, 미화 및 서식 도구 : JSON 온라인 서식 도구 : 온라인 XML/JSON 상호 전환 도구 : JSON 코드 온라인 서식/미화/압축/편집/변환 도구 : 온라인 JSON 압축/탈출구 : C 언어 스타일/HTML/CSS/JSON 코드 서식 및 미화 도구 :
http://tools.vevb.com/code/json
http://tools.vevb.com/code/jsonformat
http://tools.vevb.com/code/xmljson
http://tools.vevb.com/code/jsoncodeformat
http://tools.vevb.com/code/json_yasuo_trans
http://tools.vevb.com/code/ccode_html_css_json
이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.