Android examples for File Input Output:Json
Parse a json reader into a list.
/*/*from ww w. ja v a2s . co m*/ * The MIT License (MIT) * * Copyright (c) 2014 Segment, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import android.util.JsonReader; import android.util.JsonToken; import android.util.JsonWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.segment.analytics.Utils.createMap; import static com.segment.analytics.Utils.isNullOrEmpty; public class Main{ /** Parse a json reader into a list. */ private static List<Object> readerToList(JsonReader reader) throws IOException { List<Object> list = Collections .synchronizedList(new ArrayList<Object>()); reader.beginArray(); while (reader.hasNext()) { Object value = readValue(reader); list.add(value); } reader.endArray(); return list; } private static Object readValue(JsonReader reader) throws IOException { JsonToken token = reader.peek(); switch (token) { case BEGIN_OBJECT: return readerToMap(reader); case BEGIN_ARRAY: return readerToList(reader); case NUMBER: return reader.nextDouble(); case STRING: return reader.nextString(); case BOOLEAN: return reader.nextBoolean(); case NULL: reader.nextNull(); return null; default: throw new IllegalStateException("Got token " + token); } } /** Parse a json reader into a map. */ private static Map<String, Object> readerToMap(JsonReader reader) throws IOException { Map<String, Object> map = createMap(); reader.beginObject(); while (reader.hasNext()) { String key = reader.nextName(); map.put(key, readValue(reader)); } reader.endObject(); return map; } }