判断 JSON 是 JSONObject 还是 JSONArray [英] Determine whether JSON is a JSONObject or JSONArray

查看:74
本文介绍了判断 JSON 是 JSONObject 还是 JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将从服务器接收 JSON 对象或数组,但我不知道它会是哪一个.我需要使用 JSON,但要这样做,我需要知道它是对象还是数组.

I am going to receive either a JSON Object or Array from server, but I have no idea which it will be. I need to work with the JSON, but to do so, I need to know if it is an Object or an Array.

我正在使用 Android.

I am working with Android.

有没有人有这样做的好方法?

Does any one have a good way of doing this?

推荐答案

我找到了更好的确定方法:

I found better way to determine:

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  //you have an object
else if (json instanceof JSONArray)
  //you have an array

tokenizer 能够返回更多类型:http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()

tokenizer is able to return more types: http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()

这篇关于判断 JSON 是 JSONObject 还是 JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆