knagode
knagode

Reputation: 6125

Detect type of JSON attribute

JSON:

{"attribute1":11, "attribute2":"string atribute"}

I want to detect what kind of type are attribute1 and attribute2:

jsonObject.getAttributeType("attribute2"); // should output: string/integer/boolean.

It was very easy to achieve in PHP or OBJC. Suggestions?

Upvotes: 1

Views: 946

Answers (2)

Thiyan Arumugam
Thiyan Arumugam

Reputation: 109

Another solution you can use the jackson library to do this,

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;

//Defining the JSON object
JSON json = {"attribute1":11, "attribute2":"string atribute"};

//Get the needed attribute
String value = json.get("attribute1");

//Convert the attribute to JsonNode
JsonNode value = JsonLoader.fromString(value);

//Then you can check type as below
value.isObject();
value.isArray();
value.isDouble();
value.isTextual();
value.isInt()

Upvotes: 0

Stephen C
Stephen C

Reputation: 719259

(I'm assuming that the Android for the org.json package is that same as you can find on the json.org site ... here.)

The only method on a JSONObject that will give you the underlying value ... without coercing it ... is JSONObject.get(name). If name is known, the result is the object that represents the value internally. I haven't done a comprehensive trawl of the code, but I think it can only be one of the following types:

  Boolean, Long, Double, String, JSONArray, JSONObject

You should be able to discriminate these using instanceof.


But should be asking yourself if this is the right thing to do. The normal way to deal with JSON object attributes via the JSONObject API is to use the methods that coerce them into the type that you expect. In most cases, it doesn't matter if a number is sent as 42 or 42.0 or "42" ... and it is best not to be picky if the intent is easy to determine.

Upvotes: 2

Related Questions