1

JSON:

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

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

  • attribute1 is integer
  • attribute2 is string

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

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

1
  • 2
    Can't you use jsonObject.get() and check result with instanceof? Commented Jul 9, 2013 at 22:44

2 Answers 2

2

(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.

Sign up to request clarification or add additional context in comments.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.