converting string into json array with GSON - java

I am trying to convert string into json array and the iterate over it.
String name = "lokesh";
String response = "[{"name":"lokesh"}, {"name":"cherukuri"}]";
JsonArray jsonArray = gson.fromJson(response, JsonArray.class);
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
System.out.println(jsonObject.get("name"));
if (jsonObject.get("name").toString().equals(name)) {
System.out.println("equal");
}
}
Problem: The If condition inside loop is not true because of quotes. because this line
System.out.println(jsonObject.get("name")); // printed "lokesh"
and System.out.println(name); //printed lokesh
Am i using GSON in a wrong way?

To get the value of the "name" attribute, you need to:
jsonObject.getString("name")
So, your code should be:
System.out.println(jsonObject.getString("name"));
if (jsonObject.getString("name").equals(name)) {
System.out.println("equal");
}

That's because jsonObject.get("name") return a JsonElement object.
If you're sure it's an string, you can get the content by
jsonObject.get("name").getAsString()

Related

Reading JSON from Java

I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.

Extract JSON array using Simple Json Library

My JSON data look like this.
{"Users":[
{"Username":"Admin1", "Password":"123"},
{"Username":"Admin2", "Password":"456"},
{"Username":"Admin3", "Password":"789"}
]}
I am trying to extract out all the list of Username and Password.
JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./Database/Users.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray userArray = (JSONArray) jsonObject.get("Users");
How do I then iterate through this JSONArray to achieve what I wanted?
Sorry if I wasn't clear. I was using org.json.simple, not org.json. And the JSONArray does not have the int length() method.
What I did was
Iterator<JSONObject> iterator = userArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
String userName = (String) factObj.get("Username");
String passWord = (String) factObj.get("Password");
}
Read the javadoc ;)
If you are using org.json.JSONArray, you can loop using int length() to know the array's length and Object get(index) or JSONObject getJSONObject(index) to get an item of the array.
You can iterate with for loop
for (int i = 0; i < userArray.length(); ++i) {
JSONObject user = recs.getJSONObject(i);
...
}
you can probably do something like the following
for(int i = 0; i < userArray.length; i++) {
JSONObject user = userArray.getJSONObject(i);
String username = user.getString("Username");
String password = user.getString("Password");
//etc
}

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

json in java getting the correct values from a list

I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:
{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}
This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.
How can I get the "Name":"Malmo" and so on....
???
The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...
JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
//Test
for (String name: names) {
System.out.println(name);
}

org.json.JSONException: "JSON object not found in JSON array"

A very simple JSON like this (response.getBody().toString()):
{"per_page":50,"total":93,"last_page":2,"stars":[]}
Has some problems when I want to parse it:
JSONObject object = new JSONObject(response.getBody()); // no error
System.out.println(object.getJSONObject("total")); // not found
org.json.JSONException: JSONObject["total"] not found.
Other properties cannot be parsed either:
JSONArray startups = object.getJSONArray("stars");
org.json.JSONException: JSONObject["stars"] not found.
The key is to hold the value of response.getBody()
String json = response.getBody().toString();
Inside object total is not JSONObject it is an Int value, that's why you code crashing.
So use this
System.out.println(String.valueOf(object.getInt("total")));
instead of
System.out.println(object.getJSONObject("total"));
String json = "{\"per_page\":50,\"total\":93,\"last_page\":2,\"stars\":[]}":
JSONObject jsonObject = new JSONObject (json);
JSONArray jsonArray = jsonObect.getJSONArray("stars");
int perPage = jsonObject.getInt("per_page");
try like this...
In addition to earlier answer, to parse array, use getJSONArray as
JSONArray ja = jsonObj.getJSONArray("stars");
You can loop-over the array as:
for(int j=0; j<ja.length(); j++) {
JSONObject json = ja.getJSONObject(j);
// do same as before for string, int or other data types
}

Categories