Getting a Value from a JsonArray using gson - java

I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson

You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");

array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}

Related

JSON : how to save JSON Array using Java and loop till last JSON Object

I'm new to JSON and have below file. I have to save the array "steps" in java and need to loop the objects "duration" , "status" and "Keyword".
"steps": [
{
"result": {
"duration": 7128811788,
"status": "passed"
},
"line": 5,
"name": "The Browser is Launched and Smart Business URL is loaded",
"match": {
"location": "Common_Login.the_Browser_is_Launched_and_Smart_Business_URL_is_loaded()"
},
"keyword": "Given "
},]
I tried below but didn't worked.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./target/JSON/Output.json"));
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) jsonArray.get(i);
name = (String) jsonObjectRow.get("duration");
id = (String) jsonObjectRow.get("status");
uri = (String) jsonObjectRow.get("name");
status = (String) jsonObjectRow.get("location");
}
Refer here.
There are so many libraries build in for doing this task. But look at the question above.
If you want to use the built-in class from Java you can have a look here:
https://stackoverflow.com/a/17399110/3977134
You are missing the part from the parseJson function in the referenced answer.
For simplicity I'd suggest to you to use org.json which is just one of many good libraries to use for JSON parsing in Java. If you are interested see here:
Parse JSON with org.json
Parsing JSON in Java Using org.json

Java GSON - make array from String of json

I want to make an array of product objects from a json file which is currently a String.
{
"invoice": {
"products": {
"product": [
{
"name": "Food",
"price": "5.00"
},
{
"name": "Drink",
"price": "2.00"
}
]
},
"total": "7.00"
}
}
...
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("product");
the line below give me: java.lang.NullPointerException
for(JsonElement element: jsonArray) {
//do stuff
System.out.println(element);
}
some code goes here...
product = new Product(name, price);
List<Product> products = new ArrayList<Product>();
products.add(product);
You have to traverse the whole JSON string to get to the "product" part.
JsonArray jsonArray = jsonObject.get("invoice").getAsJsonObject().get("products").getAsJsonObject().get("product").getAsJsonArray();
I would recommend that you create a custom deserializer as described in the second answer to this question: How do I write a custom JSON deserializer for Gson? This will make it a lot cleaner, and let you handle improper JSON and make it easier in case your JSON ever changes.
I think you can use Gson library for this
You can find the project and the documentation at : https://github.com/google/gson/blob/master/README.md
try
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject invoice = parser.parse(jsonString).getAsJsonObject();
JsonObject products = invoice.getAsJsonObject("products");
JsonArray jsonArray = products.getAsJsonArray("product");

Parsing Nested JSON Array with json-simple [duplicate]

This question already has answers here:
How do I parse a JSONArray in Java with Json.simple?
(3 answers)
Closed 7 years ago.
Trying to use json simple to parse data from rest service. The response looks like:
{
"locations": [
"city" : "San Jose",
"state" : "Ca",
"job" : {
"site" : "Main Processing",
"region" : "USA"
}
]
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray array = (JSONArray) jsonObject.get("locations");
for(int i = 0; i < array.size(); i++) {
String site = array.getJSONObject(i).getString("site");
}
My issue is I am having trouble getting a reference to the job element from JSONArray object. The "locations" reference is basic parsing but the "job" reference is giving me issue when its defined inside an array.
Also getJSONObject does not seem to be a valid method to JSONArray.
Can this be done with the json-simple library?
The getJSONObject method is provided by the org.json.JSONArray class. (without using json-simple). I can not find it in the json-simple doc. So using the org.json.* package import, you can do:
JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray array = jsonObject.getJSONArray("locations");
//You should check that array.length() >= 3
JSONObject job = array.getJSONObject(2);
String site = job.getString("site");

How to get data from JSONobject and display it into a listview?

This is my JSON
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
Now I am trying to display it into a listView how would I do that this is what i have right now (for testing purposes i am just trying to display all the names in a toast)
JSONObject jsonObj = new JSONObject(jsonStr);
int length = jsonObj .length();
for(int i=0; i<length; i++) {
Toast.makeText(this, jsonObj.getJSONArray("data").
getJSONObject(i).getString("Name"), Toast.LENGTH_LONG).show();
}
The Above code only display one name and not multiple names. How can I make it for multiple names?
Take a look this code snippet
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name").toString(), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name").toString(), Toast.LENGTH_LONG).show();
}
}
I recommend to use 'Log' instead using 'Toast'.
If any confusion or query let me know, i will try my best to resolve it.
If answer is satisfiable please mark it as correct answer.
Happy coding!
Thanks
You are getting the length of JSONObject, but you should get the length of JSONArray inside that JSONObject in order to iterate though json array items.
int length = jsonObj.getJSONArray("data").size()
I think you are guessing it wrong. Look closely you have a Json in that you have array which is JsonArray with the name/key "data"
then in that you can get it and traverse it index by index. For you I am providing you a road map so that things make easy for you conceptually
Make a model class which may able to store the values as you are getting in response of your api or in this json respone.
Take an array of type of your model class to store values
Now you can add for loop to save values or you can parse and save your jason array into your array you made to handle the jasonarray
this is easily be understand by this link and this is a working example to parse the json array and to show in your list view. You have nothing to worry about after reading these two links.
get your result from URL where your json is and store to any variable (result here) , then decode it i am showing below,
try this , it may give you some hint , i have not tried but may help you
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.optJSONArray("data");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
int id = jsonObjects.optInt("id");
String varMessage = jsonObjects.optString("varMessage");
String Image = jsonObjects.optString("Image");
String Category = jsonObjects.optString("Category");
String Method = jsonObjects.optString("Method");
JSONArray jsonArrayIngredients = jsonObject.optJSONArray("Ingredients");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String name = jsonObjects.optString("name");
}
}
}

Reading JSON file using json-smart

I am trying to read the values from a JSON file to array for further processing. I am using JSON-Smart 1.2.0 library for the same. Due to some restrictions, I can not use the 2.0 version.
I am getting the following exception.
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject
I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?
Below is the java code.
JSONObject json = (JSONObject) JSONValue.parseWithException(browsers);
JSONArray array = (JSONArray) json.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
Below is the json file content.
[
{
"friends": [
{
"id": 0,
"name": "test1"
},
{
"id": 1,
"name": "test2"
}
]
}
]
Your JSON contains an array which has one single object element so you should parse it like that:
JSONArray root = (JSONArray) JSONValue.parseWithException(json);
JSONObject rootObj = (JSONObject) root.get(0);
JSONArray array = (JSONArray) rootObj.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
If it can have more elements add a for loop instead of root.get(0).

Categories

Resources