Detect type of JSON attribute - java

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?

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

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

Related

Jython: Parse JSON object to get value (object has array)

I have JavaScript that parses a JSON object (object has array) and returns the value from the ZONE field.
var obj = JSON.parse(json_text);
parsed_val = obj.features[0].attributes.ZONE
I would like to convert the JavaScript code to Jython.
This is what I've tried:
from com.ibm.json.java import JSONObject
obj = JSONObject.parse(json_text)
parsed_val = obj.get('features.attributes.ZONE');
The Jython compiles, but it doesn't return a valid value (it returns None). I think this is because I haven't referenced the array properly.
How can I parse the JSON object/array using Jython to get the ZONE value?
(Jython version is 2.7.0. However, I can't seem to use Python's JSON library (normally included in Jython)).
I needed to use get() at each level of the object.
As well as specify the array's index position after the first level: [0].
from com.ibm.json.java import JSONObject
obj = JSONObject.parse(json_text)
parsed_val = obj.get("features")[0].get("attributes").get("WEEK")
Credit goes to #vikarjramun for pointing me in the right direction. Thanks.

How to convert Complex JSON string in to MAP in scala

I have a text file which contains a line like
players={"Messi":{"Details":{"Goals":500},"Country":"Argentina"},"Neymar":{"Clubs":["Santos", "FC barcelona", "Paris saint German"], "Country":"Brazil"}}
Now I am used a regex for extract the
{"Messi":{"Details":{"Goals":500},"Country":"Argentina"},"Neymar":{"Clubs":["Santos", "FC barcelona", "Paris saint German"],"Country":"Brazil"}}
from the text file and pass it in to a case class which accepts the value as a String.
and I am making a Dataframe using this case class.
In my case every line may be different in the contents with in the JSON String.So I am looking for a general solution to Convert any complex Json string to Map values.
When checking dataframe.printSchema, I am getting the players column as a String type.
But I need it to be as a Map type which holds a Key and value as a Struct type.
I tried method referred in this link
How can I convert a json string to a scala map?
when I used this way,I got error
"org.json4s.package$MappingException: Do not know how to convert JObject(List((Details,JObject(List((Goals,JString(500))))), (Country,JString(Argentina)))) into class java.lang.String "
and I used following solutions
Converting JSON string to a JSON object in Scala
But these too won't worked for me.
This is my case class
case class caseClass (
Players :String = ""
)
I am Extracting the json string using a user defined function.
Simply my requirement is that I have a complex Json String which contains keys and values as struct,list etc..
so I want to make the string to its corresponding JSON which holds a proper schema with respect to its contents.
Kindly expecting Valuable solutions.
If you also can live with JsValue as value instead of String it looks a bit simpler:
import play.api.libs.json._
case class CaseClass (
Players :Option[JsValue]
)
object CaseClass {
implicit val jsonFormat = Json.format[CaseClass ]
}
I saw some problems with your Json - so you would need to have something like:
val json = Json.parse("""{
"Players":{
"Messi":{"Details":{"Goals":500},"Country":"Argentina"},
"Neymar":{"Clubs":["Santos", "FC barcelona", "Paris saint German"], "Country":"Brazil"}
}
}"""
)
To get a String out of this you can use:
json.validate[CaseClass] match {
case JsSuccess(cc, _) => cc.Players.toString
case JsError(errors) => // handle errors
}
I got another solution which I think More easier.
I Made an own schema for the JSON and Used from_json method with the schema,and it worked well.
from_json(col("Players"),ownschema).as("new_Json")
and my ownschema contains the structure of the Json String.
For any doubts, Comment.
Happy Coding.

Can't get value from JSONObject

So I am using the simple json library to perform some json operations. Right now I can construct a JSONObject from a json string but I am not able to get the value from the object I created.
For example if I do something like:
String value = (String) jsonRecord.get("Key");
I will get an error saying:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
I removed the type cast to string and it works in IntelliJ. However, when I do this at command line it gives me an error saying:
error: incompatible types: Object cannot be converted to String
The schema is as follows:
{
"myArray": {
"array": ["Decaf mocha", "Vanilla mocha", "Chai Latte"]
},
"Item": {
"string": "Decaf macha"
}
}
Update: the toString() fixed the problem. But when I tried to get the array I am getting:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
Can someone please suggest how to fix the problem? Thanks!
Your value is a JSONObject, not a string. Your error message makes that quite clear. If you really want it as a string, use
String value = jsonRecord.get("Key").toString();
You can pass any object to System.out.println, not just strings, but to actually turn it to a string, you need to call toString() yourself.
However, if you're expecting an actual String as the Key, and not a JSONObject, then you should take a second look at your JSON, because you're doing something wrong.
UPDATE:
Okay, looking at your schema, I see the problem. Instead of mapping the keys to values directly, your JSON maps keys to objects which then contain values. So to get the array in the JSON you posted, instead of
value = jsonRecord.get("myArray")
you would use
JSONArray value = jsonRecord.getJSONObject("myArray").getJSONArray("array");
and for the string, you would use
String value = jsonRecord.getJSONObject("Item").getString("string");
Just need to add the current "org.json" dependency would resolve your issue as latest version holds get() method (JSONObject class) which returns Object.
Below is my maven dependency:-
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
Below is my code which performs get key operation.
public void iterateJsonObject(JSONObject jsonObj) {
jsonObj.keySet().forEach(keyStr ->
{
Object keyvalue = jsonObj.get(keyStr);
System.out.println("key: "+ keyStr + " value: " + keyvalue);
});
}
You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
You are not converting the json record value that you are fetching into a string.
String value = String.valueOf(jsonRecord.get("Key"));
his should fix your problem. You can also use toString() method but I personally prefer String.valueOf() over it because at times toString() tends to give garbage value.

Converting JSONObject to JSON using GSON

I am having an Java Object which consist many type of variables including a JSONObject.
Whan i debug my object i got the following String for JSONObject:-
{"INCLUSIONS":{"OPTIONS":[{"display":"Complimentary stay for children under 5 without extra bed"}]}}
But when i used:-gson.toJson(JSONObj),I got following
{"myHashMap":{"INCLUSIONS":{"myHashMap":{"OPTIONS":{"myArrayList":[{"myHashMap":{"display":"Complimentary stay for children under 5 without extra bed"}}]}}}}}
Someone please can elaborate why it is converting JSONObject to Map & list ??
Or Any work Around ??
Thanks.
Just use myJsonObj.toString() instead of myJsonObj.toJSON()
Your problem happens because a JSONObject is stored as a HashMap to allow the programmer to reach values with methods based on keys. As example,
String jsonStr = "{'key': 'value'}";
JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
String value = json.get("key").getAsString();
You can figure that json attributes are stored as a HashMap<JsonElement>

Parsing this JSON with Java?

When Parsing JSON I normally just constuct an object and use the gsonlibrary to parse my String into that object.
However, I now find myself with a rather complex response which consists of many elements each with sub elements of objects and arrays and arrays of objects. It looks something like this...
{
"type": "thetype",
"object":{
"text": "texthere",
"moretext": "more here"
},
...,
...,
...,
...,
"fieldIwant": [
{
"object":"object!"
},
....
....
{
"object":"object!"
},
]
}
The thing is, I'm only really interested in fieldIwantand nothing else. Is there not a way in Java for me to just extract that field and work with it alone and not all this other dead weight I do not need?
According to this http://sites.google.com/site/gson/gson-design-document it looks like gson does this for you by default.
When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected.
In other words, it doesn't deserialize any of the fields you don't need. You should be good to go.
You can use the low level JsonParser API
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
yourArray = new Gson().fromJson(jsonObject.get("fieldIwant"), yourArrayType);
Alternatively you can create an ExclusionStrategy to use with a GsonBuilder

Categories

Resources