当前位置: 移动技术网 > IT编程>开发语言>Java > Simple JSON开发指南

Simple JSON开发指南

2019年07月22日  | 移动技术网IT编程  | 我要评论

simple json是google开发的 json解析框架,基于apache协议。

json-simple的主页:

下载的文件是: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); 

jsonobject是继承map的,而jsonarray是继承list的,所以你可以用map和list的标准方式来使用jsonobject和jsonarray。

而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:容器工厂

使用使用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; 
   } 
    
  } 
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 。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网