Reputation: 133
I'm trying to retrieve Value i.e., 80000
where Name is "Camera" from the Product's JSON using java. Can anyone please help me out ?
{
"Products":{
"Product":[
{
"Name":"Tv",
"Value":50000
},
{
"Name":"Camera",
"Value":80000
},
{
"Name":"Phone",
"Value":15000
},
]
}
}
JSONObject arrayOfProducts = jsonObj.optJSONObject("Products");
JSONArray products = arrayOfProducts.getJSONArray("Product");
for (int i = 0; i < products.length(); i++) {
JSONObject objects = products.getJSONObject(i);
Iterator key = objects.keys();
while (key.hasNext()) {
String k = key.next().toString();
if(k.equals("Name")) {
if(objects.getString(k).equals("Camera")) {
System.out.println("Key : " + k + ", value : " + objects.getString(k));
}
}
}
Upvotes: 0
Views: 8739
Reputation: 19
Why you need to choose complex solution to parse JSON like that?
You should use define some entities and then use library for reading JSON value (Ex: "ObjectMapper" of jackson) to parser it to Object.
You can leave all complex parts for them, after that you just working on java object.
Upvotes: 0
Reputation: 3066
If you want to get the value in a key-value pair in a JSON you need to use the following syntax:
[JSONObject].get[data_type]([key_name])
.
In the above given syntax, replace the [JSONObject]
with the
variable of type JSONObject
representing the JSON. In your case,
it is objects
.
replace [data_type]
with the data type of the value at that particular key. In the
current case, value for the key "Value"
is 80000
is an Integer
.. Hence it
should be getInt
.
Replace [key_name]
with the key whose value you need to retrieve, which in your
case is "Value"
.
Hence the code snippet you need to use to get the value 80000 which with the "Camera" part is: objects.getInt("Value")
.
Here is your overall updated code:
JSONObject arrayOfProducts = jsonObj.optJSONObject("Products");
JSONArray products = arrayOfProducts.getJSONArray("Product");
for (int i = 0; i < products.length(); i++) {
JSONObject objects = products.getJSONObject(i);
Iterator key = objects.keys();
while (key.hasNext()) {
String k = key.next().toString();
if(k.equals("Name")) {
if(objects.getString(k).equals("Camera")) {
System.out.println("\nKey : " + k + "\nName : " + objects.getString(k) + ", \nValue : " + objects.getInt("Value"));
}
}
}
}
Upvotes: 1
Reputation: 133
Your JSON is wrong.
Correct: "Products"
Wrong: “Products”
{}
. Enclose your whole JSON file content within {}
.Upvotes: 0