Last active
January 29, 2020 13:27
-
-
Save ok3141/597dbb1e72f0933726cf6b25907f6789 to your computer and use it in GitHub Desktop.
The simplest Json parser (Android)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.util.JsonReader; | |
import androidx.annotation.NonNull; | |
import androidx.annotation.Nullable; | |
import java.io.IOException; | |
import java.io.StringReader; | |
import java.math.BigDecimal; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
public class JsonUtils { | |
@Nullable | |
public static Object readValue(@NonNull String json) throws IOException { | |
return readValue(new JsonReader(new StringReader(json))); | |
} | |
@NonNull | |
public static List<Object> readArray(@NonNull String json) throws IOException { | |
return readArray(new JsonReader(new StringReader(json))); | |
} | |
@NonNull | |
public static Map<String, Object> readObject(@NonNull String json) throws IOException { | |
return readObject(new JsonReader(new StringReader(json))); | |
} | |
@Nullable | |
public static Object readValue(@NonNull JsonReader reader) throws IOException { | |
switch (reader.peek()) { | |
case BEGIN_ARRAY: | |
return readArray(reader); | |
case BEGIN_OBJECT: | |
return readObject(reader); | |
case STRING: | |
return reader.nextString(); | |
case NUMBER: | |
return new BigDecimal(reader.nextString()); | |
case BOOLEAN: | |
return reader.nextBoolean(); | |
case NULL: | |
reader.nextNull(); | |
return null; | |
} | |
throw new IOException(String.valueOf(reader.peek())); | |
} | |
@NonNull | |
public static List<Object> readArray(@NonNull JsonReader reader) throws IOException { | |
reader.beginArray(); | |
List<Object> result = new ArrayList<>(); | |
while (reader.hasNext()) { | |
result.add(readValue(reader)); | |
} | |
reader.endArray(); | |
return result; | |
} | |
@NonNull | |
@SuppressWarnings("ConstantConditions") | |
public static Map<String, Object> readObject(@NonNull JsonReader reader) throws IOException { | |
reader.beginObject(); | |
Map<String, Object> result = new HashMap<>(); | |
while (reader.hasNext()) { | |
result.put(reader.nextName(), readValue(reader)); | |
} | |
reader.endObject(); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment