Simple JSON开发指南

本文介绍使用Simple-JSON库解析JSON数据的多种方法,包括使用JSONValue、JSONParser进行解析,异常处理,容器工厂自定义容器类型,SAX式内容处理及整个对象图的解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子1:很方便的方式,使用 JSONValue, JSONObject是继承Map的,而JSONArray是继承List的,所以你可以用Map和List的标准方式来使用JSONObject和JSONArray。

 

而JSONValue则可以使用数组也可以用对象。


 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);
例子2:快速的方式,使用 JSONParser, 使用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);
例子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);
  }

例子4:容器工厂

 

使用使用ContainerFactory类来创建一个容器工厂。

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默认使用JSONObject和JSONArray。
 例子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;
        }
        
    }
主代码:
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不是线程安全的。 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值