Simple JSON 개발 가이드

10775 단어 javaSimple
Simple JSON은 Google에서 개발한 것입니다Java JSON 해석 프레임워크, 아파치 프로토콜 기반.
json-simple 홈페이지:https://www.jb51.net/softs/455885.html
다운로드된 파일은: json_simple.jar
예1: JSONValue를 사용하는 편리한 방법

 System.out.println("=======decode======="); 
    
    String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; 
    Object obj=JSONValue.parse(s); 
    JSONArray array=(JSONArray)obj; 
    System.out.println("======the 2nd element of array======"); 
    System.out.println(array.get(1)); 
    System.out.println(); 
        
    JSONObject obj2=(JSONObject)array.get(1); 
    System.out.println("======field \"1\"=========="); 
    System.out.println(obj2.get("1"));  
  
        
    s="{}"; 
    obj=JSONValue.parse(s); 
    System.out.println(obj); 
        
    s="[5,]"; 
    obj=JSONValue.parse(s); 
    System.out.println(obj); 
        
    s="[5,,2]"; 
    obj=JSONValue.parse(s); 
    System.out.println(obj); 
JSON Object는 맵을 계승하는 것이고 JSON Array는 List를 계승하는 것이기 때문에 맵과 List의 표준 방식으로 JSON Object와 JSON Array를 사용할 수 있습니다.
JSONValue는 배열을 사용할 수도 있고 객체를 사용할 수도 있습니다.
예2: JSONParser를 사용하는 빠른 방법

 JSONParser parser=new JSONParser(); 
  
  System.out.println("=======decode======="); 
      
  String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; 
  Object obj=parser.parse(s); 
  JSONArray array=(JSONArray)obj; 
  System.out.println("======the 2nd element of array======"); 
  System.out.println(array.get(1)); 
  System.out.println(); 
      
  JSONObject obj2=(JSONObject)array.get(1); 
  System.out.println("======field \"1\"=========="); 
  System.out.println(obj2.get("1"));  
  
      
  s="{}"; 
  obj=parser.parse(s); 
  System.out.println(obj); 
      
  s="[5,]"; 
  obj=parser.parse(s); 
  System.out.println(obj); 
      
  s="[5,,2]"; 
  obj=parser.parse(s); 
  System.out.println(obj); 
JSONParser를 사용하려면 예외를 포착해야 합니다.
예 3: 예외 처리

 String jsonText = "[[null, 123.45, \"a\\tb c\"]}, true"; 
  JSONParser parser = new JSONParser(); 
      
  try{ 
  parser.parse(jsonText); 
  } 
  catch(ParseException pe){ 
  System.out.println("position: " + pe.getPosition()); 
  System.out.println(pe); 
  } 
실행 결과:

position:25 Unexpected token RIGHT BRACE(}) at position 25.
 
예 4: 용기 공장
컨테이너 팩토리 클래스를 사용하여 컨테이너 공장을 만듭니다.

 String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}"; 
  JSONParser parser = new JSONParser(); 
  ContainerFactory containerFactory = new ContainerFactory(){ 
  public List creatArrayContainer() { 
   return new LinkedList(); 
  } 
  
  public Map createObjectContainer() { 
   return new LinkedHashMap(); 
  } 
        
  }; 
      
  try{ 
  Map json = (Map)parser.parse(jsonText, containerFactory); 
  Iterator iter = json.entrySet().iterator(); 
  System.out.println("==iterate result=="); 
  while(iter.hasNext()){ 
   Map.Entry entry = (Map.Entry)iter.next(); 
   System.out.println(entry.getKey() + "=>" + entry.getValue()); 
  } 
        
  System.out.println("==toJSONString()=="); 
  System.out.println(JSONValue.toJSONString(json)); 
  } 
  catch(ParseException pe){ 
  System.out.println(pe); 
  } 
결과는 다음과 같습니다.

==iterate result== first=>123 second=>[4,5,6] third=>789 ==toJSONString()==
 {"first":123,"second":[4,5,6],"third":789}
만약 용기 공장을 사용하지 않는다면, Simple-JSON은 기본적으로 JSON Object와 JSON Array를 사용합니다.
예 5: 중지 가능한 SAX식 컨텐츠 처리
SimpleJSON은 텍스트 흐름을 처리하는 간단한 SAX 방식의 내용 처리 방식을 추천합니다. 사용자는 논리 입력 흐름의 임의의 점에 머물러서 다른 논리를 처리한 다음에 이전의 처리를 계속할 수 있습니다.전체 흐름이 끝날 때까지 기다릴 필요가 없다.다음은 하나의 예이다.
KeyFinder.java:

 class KeyFinder implements ContentHandler{ 
  private Object value; 
  private boolean found = false; 
  private boolean end = false; 
  private String key; 
  private String matchKey; 
    
  public void setMatchKey(String matchKey){ 
  this.matchKey = matchKey; 
  } 
    
  public Object getValue(){ 
  return value; 
  } 
    
  public boolean isEnd(){ 
  return end; 
  } 
    
  public void setFound(boolean found){ 
  this.found = found; 
  } 
    
  public boolean isFound(){ 
  return found; 
  } 
    
  public void startJSON() throws ParseException, IOException { 
  found = false; 
  end = false; 
  } 
  
  public void endJSON() throws ParseException, IOException { 
  end = true; 
  } 
  
  public boolean primitive(Object value) throws ParseException, IOException { 
  if(key != null){ 
   if(key.equals(matchKey)){ 
   found = true; 
   this.value = value; 
   key = null; 
   return false; 
   } 
  } 
  return true; 
  } 
  
  public boolean startArray() throws ParseException, IOException { 
  return true; 
  } 
  
    
  public boolean startObject() throws ParseException, IOException { 
  return true; 
  } 
  
  public boolean startObjectEntry(String key) throws ParseException, IOException { 
  this.key = key; 
  return true; 
  } 
    
  public boolean endArray() throws ParseException, IOException { 
  return false; 
  } 
  
  public boolean endObject() throws ParseException, IOException { 
  return true; 
  } 
  
  public boolean endObjectEntry() throws ParseException, IOException { 
  return true; 
  } 
 } 
Main logic:

String jsonText ="{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}";
 JSONParser parser =newJSONParser();
 KeyFinder finder =newKeyFinder();
 finder.setMatchKey("id");
 try{
 while(!finder.isEnd()){
  parser.parse(jsonText, finder,true);
  if(finder.isFound()){
  finder.setFound(false);
  System.out.println("found id:");
  System.out.println(finder.getValue());
  }
 }   
 }
 catch(ParseException pe){
 pe.printStackTrace();
 }
실행 결과:

found id:
 id1
 found id:
 123
 found id:
 null
예 6: 전체 객체 맵, SAX식 해석

 class Transformer implements ContentHandler{ 
   private Stack valueStack; 
    
   public Object getResult(){ 
    if(valueStack == null || valueStack.size() == 0) 
     return null; 
    return valueStack.peek(); 
   } 
    
   public boolean endArray () throws ParseException, IOException { 
    trackBack(); 
    return true; 
   } 
  
   public void endJSON () throws ParseException, IOException {} 
  
   public boolean endObject () throws ParseException, IOException { 
    trackBack(); 
    return true; 
   } 
  
   public boolean endObjectEntry () throws ParseException, IOException { 
    Object value = valueStack.pop(); 
    Object key = valueStack.pop(); 
    Map parent = (Map)valueStack.peek(); 
    parent.put(key, value); 
    return true; 
   } 
  
   private void trackBack(){ 
    if(valueStack.size() > 1){ 
     Object value = valueStack.pop(); 
     Object prev = valueStack.peek(); 
     if(prev instanceof String){ 
      valueStack.push(value); 
     } 
    } 
   } 
    
   private void consumeValue(Object value){ 
    if(valueStack.size() == 0) 
     valueStack.push(value); 
    else{ 
     Object prev = valueStack.peek(); 
     if(prev instanceof List){ 
      List array = (List)prev; 
      array.add(value); 
     } 
     else{ 
      valueStack.push(value); 
     } 
    } 
   } 
    
   public boolean primitive (Object value) throws ParseException, IOException { 
    consumeValue(value); 
    return true; 
   } 
  
   public boolean startArray () throws ParseException, IOException { 
    List array = new JSONArray(); 
    consumeValue(array); 
    valueStack.push(array); 
    return true; 
   } 
  
   public void startJSON () throws ParseException, IOException { 
    valueStack = new Stack(); 
   } 
  
   public boolean startObject () throws ParseException, IOException { 
    Map object = new JSONObject(); 
    consumeValue(object); 
    valueStack.push(object); 
    return true; 
   } 
  
   public boolean startObjectEntry (String key) throws ParseException, IOException { 
    valueStack.push(key); 
    return true; 
   } 
    
  } 
Main 방식 논리:

 String jsonString = <Input JSON text>; 
  Object value = null; 
  JSONParser parser = new JSONParser(); 
  Transformer transformer = new Transformer(); 
    
  parser.parse(jsonString, transformer); 
  value = transformer.getResult(); 
실행 결과:

String jsonString =<Input JSON text>;
 Object value =null;
 JSONParser parser =newJSONParser();
 value = parser.parse(jsonString);
참고:
JSONPauser는 스레드가 안전하지 않습니다. 
json_encode - 변수를 JSON 인코딩합니다.
설명:string json_encode($value),value 값의 JSON 형식을 반환합니다.
매개 변수: 인코딩할 value,resource 형식을 제외한 모든 데이터 형식
이 함수는 UTF-8 인코딩된 데이터만 사용할 수 있습니다(역주: 문자/문자열 유형의 데이터).
반환값: 인코딩이 성공하면 JSON 형식으로 표시된string을 반환합니다.

좋은 웹페이지 즐겨찾기