Java 如何检查给定对象是JSON字符串中的对象还是数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9817315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether the given object is object or Array in JSON string
提问by Judy
I am getting JSON string from website. I have data which looks like this (JSON Array)
我从网站获取 JSON 字符串。我有看起来像这样的数据(JSON 数组)
myconf= {URL:[blah,blah]}
but some times this data can be (JSON object)
但有时这些数据可以是(JSON 对象)
myconf= {URL:{try}}
also it can be empty
也可以为空
myconf= {}
I want to do different operations when its object and different when its an array. Till now in my code I was trying to consider only arrays so I am getting following exception. But I am not able to check for objects or arrays.
我想在它的对象和不同的数组时做不同的操作。直到现在在我的代码中,我试图只考虑数组,所以我遇到了以下异常。但我无法检查对象或数组。
I am getting following exception
我收到以下异常
org.json.JSONException: JSONObject["URL"] is not a JSONArray.
Can anyone suggest how it can be fixed. Here I know that objects and arrays are the instances of the JSON object. But I couldn't find a function with which I can check whether the given instance is a array or object.
任何人都可以建议如何修复它。在这里我知道对象和数组是 JSON 对象的实例。但是我找不到可以检查给定实例是数组还是对象的函数。
I have tried using this if condition but with no success
我试过使用这个 if 条件但没有成功
if ( myconf.length() == 0 ||myconf.has("URL")!=true||myconf.getJSONArray("URL").length()==0)
采纳答案by cHao
JSON objects and arrays are instances of JSONObject
and JSONArray
, respectively. Add to that the fact that JSONObject
has a get
method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions, and there ya go.
JSON 对象和数组分别是JSONObject
和 的实例JSONArray
。除此之外,JSONObject
还有一个get
方法可以返回一个对象,您可以检查自己的类型而不必担心 ClassCastExceptions,然后就可以了。
if (!json.isNull("URL"))
{
// Note, not `getJSONArray` or any of that.
// This will give us whatever's at "URL", regardless of its type.
Object item = json.get("URL");
// `instanceof` tells us whether the object can be cast to a specific type
if (item instanceof JSONArray)
{
// it's an array
JSONArray urlArray = (JSONArray) item;
// do all kinds of JSONArray'ish things with urlArray
}
else
{
// if you know it's either an array or an object, then it's an object
JSONObject urlObject = (JSONObject) item;
// do objecty stuff with urlObject
}
}
else
{
// URL is null/undefined
// oh noes
}
回答by Oh Chin Boon
Quite a few ways.
好几种方式。
This one is less recommended if you are concerned with system resource issues / misuse of using Java exceptions to determine an array or object.
如果您担心系统资源问题/滥用 Java 异常来确定数组或对象,则不建议使用此方法。
try{
// codes to get JSON object
} catch (JSONException e){
// codes to get JSON array
}
Or
或者
This is recommended.
这是推荐的。
if (json instanceof Array) {
// get JSON array
} else {
// get JSON object
}
回答by Shailesh
Using @Chao answer i can solve my problem. Other way also we can check this.
使用@Chao 回答我可以解决我的问题。其他方式我们也可以检查这个。
This is my Json response
这是我的 Json 回复
{
"message": "Club Details.",
"data": {
"main": [
{
"id": "47",
"name": "Pizza",
}
],
"description": "description not found",
"open_timings": "timings not found",
"services": [
{
"id": "1",
"name": "Free Parking",
"icon": "http:\/\/hoppyclub.com\/uploads\/services\/ic_free_parking.png"
}
]
}
}
Now you can check like this that which object is JSONObject
or JSONArray
in response.
现在你可以像这样检查哪个对象是JSONObject
或JSONArray
响应。
String response = "above is my reponse";
if (response != null && constant.isJSONValid(response))
{
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJson = jsonObject.getJSONObject("data");
Object description = dataJson.get("description");
if (description instanceof String)
{
Log.e(TAG, "Description is JSONObject...........");
}
else
{
Log.e(TAG, "Description is JSONArray...........");
}
}
This is used for check that received json is valid or not
这用于检查接收到的 json 是否有效
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
回答by AA Shakil
I was also having the same problem. Though, I've fixed in an easy way.
我也遇到了同样的问题。不过,我已经以一种简单的方式修复了。
My json
was like below:
我的json
如下所示:
[{"id":5,"excerpt":"excerpt here"}, {"id":6,"excerpt":"another excerpt"}]
Sometimes, I got response like:
有时,我得到这样的回应:
{"id":7, "excerpt":"excerpt here"}
I was also getting error like you. First I had to be sure if it's JSONObject
or JSONArray
.
我也像你一样遇到错误。首先,我必须确定它是JSONObject
还是JSONArray
。
JSON arrays are covered by [] and objects are with {}
JSON 数组由 [] 覆盖,对象由 {} 覆盖
So, I've added this code
所以,我添加了这段代码
if (response.startsWith("[")) {
//JSON Array
} else {
//JSON Object
}
That worked for me and I wish it'll be also helpful for you because it's just an easy method
这对我有用,我希望它对你也有帮助,因为这只是一个简单的方法
See more about String.startsWith here - https://www.w3schools.com/java/ref_string_startswith.asp
在此处查看有关 String.startsWith 的更多信息 - https://www.w3schools.com/java/ref_string_startswith.asp