How to get value by key from JSON? - java

JSON looks like:
{
"cover":"blabla.jpg",
"content":[
{
"article":"article_text",
"document":"document_text"
}
]
}
I know how to get "cover":
JSONObject json = new JsonObject(jsonStr);
json.get("cover");
But how can I get value by "article" key?

You can try something like this:
yourJSonObject.getJSONObject("cover").getJSONObject("content").getJSONObject("article");

Oh, i did it. Thanks.
json.getJSONArray("content").getJSONObject(0).getString("article")

"content" in that position it´s just a String, so at first place you have to create a new JSONObject from that String and then you can access to his properties like this
JSONObject content = new JSONObject(yourJSonObject.getString("content"));
String article = content.getString("article");

Related

How to handle the case when field is not present in Object Java?

I have an object something like this in my database and now my requirement is to find the value of particular field such as name and if present return true,
{
"_id" : "123",
"name" : "Team"
}
but in some case the field name itself doesn't exist. Sample can be something like this:
{
"id":1234
}
In this case I need to return false.
How can I validate if name field exist in particular object?
I was trying to use StringUtils method something like this
StringUtils.isBlank(obj.getName); But its throwing It is throwing java.lang.NullPointerException .
You can use Json schema validator. If your json will be in specific format. Please have a look at Jackson library.
JSONObject class has a method named "has". try this way,
if (json.has("name")) {
String status = json.getString("name"));
}
This will work
You can use Gson Java library to serialize and deserialize Java objects to JSON (as given below).
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(object, JsonObject.class);
Then, you can use the has method in JsonObject, to check if the key exists in it.
jsonObject.has(key)
Example:
Below is a method to check if given key exists in given json string, and get it's value.
(Instead of String, you can use your object as well. Here, I am considering the jsonStr as a String object, for better understanding.)
private String getValueFromJsonForGivenKey(String key, String jsonStr) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
if (jsonObject.has(key)) {
// The given JSON string has the given key
String value = jsonObject.get(key).getAsString();
return value;
}
return null;
}
For key id and for jsonStr { "id": "1234" }, we get 1234.
For key name and for jsonStr { "id": "1234" }, we get null.
What you can do is to use JSONObject's opt method
eg.
JSONObject jsonObject = new JSONObject(myJSONString);
String name = jsonObject.optString("name");

Value as string array in gson key value

I'm new to JSON. I'm trying to assign value (in key value pairs) as array of strings using GSON.
The JSON should look like as below:
{ "name": "path", "value": [ "/my-path" ,"/my-path2","/newpath"] }
How can I achieve this?
Thanks.
Even thoe I will hardly recommend you to use POJOS, gson is flexible enough to allow you to do what you want:
JsonObject jo = new JsonObject();
jo.addProperty("name", "path");
JsonArray jsonArray = new JsonArray();
jsonArray.add("my-path");
jsonArray.add("my-path2");
jsonArray.add("my-new-path");
jo.add("value", jsonArray);
System.out.println(jo);

JSONObject not workign

I am building an app for android.
I fire and HTTP GET request and this request returns a JSONObject. I want to retrieve the value by key. But this is not working properly.
This is the JSONObject named obj that I receive:
{"id":1,"name":"math","description":"This is a math course."}
If I log Log.d("title", String.valueOf(obj.has("name"))); this will result into true.
This works for all keys in the JSONObject.
But if I want to receive the name and do this so:
Log.d("title", obj.getString("name"));
I will get an unhandled exception: org.json.JSONException.
Does anybody know how I can fix this problem?
Maybe you should try someting like this:
Log.d("title", obj.name);
var obj = $.parseJSON('{"id":1,"name":"math","description":"This is a math course."}');
alert(obj['name']);
Try this :) You can use JSON.parse insted of $.parseJSON if you are not using jquery. Following in Java
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
Everything between the { } makes part of an array, so you first need to get a JSONArray like this:
JSONArray myJSONArray = obj.getJSONArray();
And then you can access the field values with:
myJSONArray.getString("name") etc...
Search on google how to work with JSONArray.

Parse JSON using JSON Object

MY JSON response body from a service as follows
{
"Employee": {
"Name": "Demo",
"applied": true
}
}
I want to parse using JSON Object in Java.
i did like this
JSONObject obj = new JSONObject(String.valueOf(responseBody));
//responbosy is a JSONObject type
obj.getString("Employee[0].name");
Please suggest how to do that
Employee is not an array, only JSONObject
So you have do something like that:
obj.getJSONObject("Employee").getString("Name");
I Think you want to have the name, yes?
Anyway, you can access it by using:
JSONObject obj = new JSONObject(String.valueOf(responseBody));
JSONObject employee = new JSONObject(obj.getJSONObject("Employee"));
employee.getString("Name");
employee.getBoolean("applied");
Reason for this is:
Everything between
{}
is an JSONObject. Everything between
[]
means it's an JSONArray.
In your String
{
"Employee": {
"Name": "Demo",
"applied": true
}
}
You've an JSONObject because of starting with {}. Within this JSONObject you have an Propertie called "Employee" which has another JSONObject nested.
Be Carefull: applied is from type boolean, since it's true/false without "". If there's a number you should get it using getInteger(). if it's a boolean you can get it using getBoolean() and elsehow you should get it using getString().
you can see all available Datatypes at http://en.wikipedia.org/wiki/JSON

Parsing JSON server response into JSON Array

I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need

Categories

Resources