Json解析

严格的格式:

[{"name":"zhangsang","age":23},{"name":"lisi","age":"36"},{"sdsd":"xad"}]

字符串必须用双引号包起来,键和值总是用‘:’号隔开,数据必须为数组或者一个{}包起来的对象。
测试用解析方法代码,流来源于文件:

	public void parse(InputStream json) throws IOException
	{
		JsonReader reader=new JsonReader(new InputStreamReader(json));
		reader.beginArray();//开始读数组
		//reader.setLenient(true); 
		while(reader.hasNext())
		{
			reader.beginObject();//开始读对象
			while(reader.hasNext())
			{
					String tag=reader.nextName();
					if(tag.equals("name"))
					{
						
					  System.out.println(reader.nextString());
					}
					else if(tag.equals("age"))
					{
						System.out.println(reader.nextString());
					}
					else
					{
						reader.skipValue();
					}
			}
			reader.endObject();
		}
		reader.endArray();
	}
当给JsonReader对象加个reader.setLenient(true);后就能读取相对较为宽松的格式了,比如:
[{name=zhangsang;"age"=>23};{"name":"lisi","age"="36"},{"sdsd":"xad"}]

对setLenient方法的说明如下:

Configure this parser to be be liberal in what it accepts. By default, this parser is strict and only accepts JSON as specified byRFC 4627. Setting the parser to lenient causes it to ignore the following syntax errors:

  • Streams that start with the non-execute prefix,")]}'\n".
  • Streams that include multiple top-level values. With strict parsing, each stream must contain exactly one top-level value.
  • Top-level values of any type. With strict parsing, the top-level value must be an object or an array.
  • Numbers may be NaNs or infinities.
  • End of line comments starting with // or # and ending with a newline character.
  • C-style comments starting with /* and ending with */. Such comments may not be nested.
  • Names that are unquoted or 'single quoted'.
  • Strings that are unquoted or 'single quoted'.
  • Array elements separated by ; instead of ,.
  • Unnecessary array separators. These are interpreted as if null was the omitted value.
  • Names and values separated by = or => instead of :.
  • Name/value pairs separated by ; instead of ,.  


  Json解析包下载地址:下载地址



你可能感兴趣的:(Json解析)