Im using GSON to parse this JSON file:
{
"database" : {
"source" : "google",
"items" : [
{"title" : "hello world",
"id" : "id_hello_world"},
{"title" : "goodbye world",
"id" : "id_goodbye_world"}
]
}
}
Which ive read into String jsonLine
Im trying to parse it and output all the values but im getting a ClassCastException at the
JsonObject source = database.getAsJsonObject("source") line.
I think im searching for the data wrong. Im using this to search and output:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = (JsonObject) jelement;
JsonObject database = jobject.getAsJsonObject("database"); //Get Database
JsonObject source = database.getAsJsonObject("source"); //Get Source
System.out.println("Source: " + source.toString()); //Print source
JsonArray items = database.getAsJsonArray("items"); //Get items array
for(int i=0; i< items.size(); i++){ //for every item
JsonObject item = (JsonObject) items.get(i); //Select item i
JsonObject title = (JsonObject) item.getAsJsonObject("title");
JsonObject id = (JsonObject) item.getAsJsonObject("id");
System.out.println("Item " + i + " title : " + title.toString() + ", id : " + id.toString());
}
If someone could correct my code that would be perfect. I know there are other simpler ways to do this using GSON.fromJSON(jsonLine, Wrapper.class) but im trying to learn to do it this way too. Thanks for the help!
Before you are going to use Gson method, create your template structure:
class Item{
private String item = "";
private String id = ""; // for sure you can use 'int'
}
public class DataBase{
private List<Item> items = null;
private String source = "";
}
Now your main class:
public class YourClass{
private DataBase database = "";
....
database = gson.fromJson(yourString, YourClass.class);
...
}
Don't forget try/catch wrapper
Enjoy
use JsonPrimitive instead of JsonObject. (it must be internal bug of GSON, because, trying to convert JsonPrimitive to JsonObject was impossible, as far as the version of GSON 2.2.3)
So, your code comes like this:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = (JsonObject) jelement;
JsonObject database = jobject.getAsJsonObject("database"); // Get
// Database
JsonPrimitive source = database.getAsJsonPrimitive("source"); // Get
// Source
System.out.println("Source: " + source.toString()); // Print source
JsonArray items = database.getAsJsonArray("items"); // Get items array
for (int i = 0; i < items.size(); i++) { // for every item
JsonObject item = (JsonObject) items.get(i); // Select item i
JsonPrimitive title = item.getAsJsonPrimitive("title");
JsonPrimitive id = item.getAsJsonPrimitive("id");
System.out.println("Item " + i + " title : " + title.toString()
+ ", id : " + id.toString());
}
As Maxim Shoustin showed, creating template will be good solution for it.
Related
JSON file:
[
{
"name":"John",
"city":"Berlin",
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"job":"Doctor"
}
]
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("F:\file.json"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
if (name.equalsIgnoreCase("john")) {
String name1 = (String) person.get("name");
System.out.println("name1" + name1);
String city1 = (String) person.get("city");
System.out.println("city1" + city1);
String job1 = (String) person.get("job");
System.out.println("job1" + job1);
person.put("city", "BLR");
String city2 = (String) person.get("city");
System.out.println("city2" + city2);
}
}
Value are not updating in Json external file
JSONObject is a represent of json that does not link to originally file.
To rewrite file you need to change values in person and write it to file.
person.put("city", "BLR");
String jsonString = person.toString();
// write jsonString to file
i am struggling with reading some values from JSON object which i get it when i hit REST API..
MY GOAL: i need to iterate over each set of data inside data object array check the value of TRAN_ID and take action accordingly.
below is the format of data
{
"data": [
{
"CUST_ID": "CUST7",
"EXPRY_DATE": null,
"PARAMS": "[{TRAN_IND:savings},{TRAN_TYP:Debit},{country:US}]"
},
{
"CUST_ID": "CUST8",
"EXPRY_DATE": null,
"PARAMS": "[{TRAN_IND:current},{TRAN_TYP:Debit},{country:US}]"
}
]
}
it looks easy and i have tried multiple solutions out there on internet but i dont know it doesnt work for me and i get below error while reading "PARAMS" and converting it to JSONArray for further processing
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
What i have tried:
private static void jsonParser(String jsonStr) throws ParseException {
JSONObject data= (JSONObject)JSONValue.parse(jsonStr );
JSONArray jsonObj = (JSONArray)data.get("data");
JSONObject JsonRow = (JSONObject)jsonObj.get(0);
JSONArray servParam= (JSONArray) JsonRow.get("PARAMS");
String tran_ind=(String) servParam.get(0);
System.out.println( tran_ind);
}
I'm guessing this is what you what?
try{
JSONObject obj = new JSONObject(sample);
JSONArray data = obj.getJSONArray("data");
for(int i=0; i<data.length(); i++){
JSONObject detail = data.getJSONObject(i);
detail.getString("CUST_ID"); //here is the customer id
detail.getString("EXPRY_DATE"); //here is the exp date
JSONArray params = detail.getJSONArray("PARAMS");
for(int j=0; j<params.length(); j++){
// {TRAN_IND:current},{TRAN_TYP:Debit},{country:US}
JSONObject res = params.getJSONObject(j);
String tran_ind = res.toString();
String tran_type = res.toString();
String country = res.toString();
out.println(tran_ind + " " +tran_type + " " + country);
}
}
}catch (JSONException ex){
ex.printStackTrace();
}
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
=> Because you are trying to parse String value "[{TRAN_IND:savings},{TRAN_TYP:Debit},{country:US}]" into the JsonArray by code:
JSONArray servParam= (JSONArray) JsonRow.get("PARAMS");
Params seems to be a String, actually.
Don't write your own parser. If you only need to read that string in each element of the array, I would simply cast the whole JSON to a Map with Jackson:
HashMap<String,Object> parsed =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
and then iterate over the "data" element (which would be a list of maps).
List<Map> data = (List) parsed.get("data");
The real problem is that those are not nested JSON strings. That would be
"PARAMS": "[{\"TRAN_IND\":\"current\"},{\"TRAN_TYP\":\"Debit\"},{\"country\":\"US\"}]"
so "text" parts are surrounded by "-s inside (which have to be escaped as \"-s).
In that case you could write
String json=
"{\n"+
" \"data\": [\n"+
" {\n"+
" \"CUST_ID\": \"CUST7\",\n"+
" \"EXPRY_DATE\": null,\n"+
" \"PARAMS\": \"[{\\\"TRAN_IND\\\":\\\"savings\\\"},{\\\"TRAN_TYP\\\":\\\"Debit\\\"},{\\\"country\\\":\\\"US\\\"}]\"\n"+
" },\n"+
" {\n"+
" \"CUST_ID\": \"CUST8\",\n"+
" \"EXPRY_DATE\": null,\n"+
" \"PARAMS\": \"[{\\\"TRAN_IND\\\":\\\"current\\\"},{\\\"TRAN_TYP\\\":\\\"Debit\\\"},{\\\"country\\\":\\\"US\\\"}]\"\n"+
" }\n"+
" ]\n"+
"}";
// Print input for clarity:
System.out.println(json);
JSONObject data= (JSONObject)JSONValue.parse(json);
JSONArray jsonObj = (JSONArray)data.get("data");
JSONObject JsonRow = (JSONObject)jsonObj.get(0);
// parse nested JSON
JSONArray servParam= (JSONArray)JSONValue.parse((String)JsonRow.get("PARAMS"));
// array element is an object ({"TRAN_IND":"savings"}), so toString has to be used:
String tran_ind=servParam.get(0).toString();
System.out.println(tran_ind);
(The backslash-heaps are there because double-quotes had to be escaped in source code, and also the suggested escaped double quotes. So they would not appear in a JSON file. Try the code in action, it prints the JSON it works on)
So (JSONArray)JSONValue.parse((String)JsonRow.get("PARAMS")) would get and parse the nested JSON.
But now you either have to rework the code what generates your input, or parse the nested non-JSON manually.
You can use below code for parsing.
String servParam = (String) JsonRow.get("PARAMS");
String servParamSplitted[] = servParam.substring(1, servParam.length() - 1).split(",");
String traind_id[] = servParamSplitted[0].substring(1, servParamSplitted[0].length() - 1).split(":");
String train_id=traind_id[1];
I like to add that your JSON should be like below format.
{
"data": [
{
"CUST_ID": "CUST7",
"EXPRY_DATE": null,
"PARAMS": [{"TRAN_IND":"savings"},{"TRAN_TYP":"Debit"},{"country":"US"}]
},
{
"CUST_ID": "CUST8",
"EXPRY_DATE": null,
"PARAMS": [{"TRAN_IND":"current"},{"TRAN_TYP":"Debit"},{"country":"US"}]
}
]
}
So, we can parse it using below code.
JSONArray servParam = (JSONArray) JsonRow.get("PARAMS");
JSONObject jsonObjectTrainID = (JSONObject) servParam.get(0);
String TrainIDValue = (String) jsonObjectTrainID.get("TRAN_IND");
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.
I am trying to make a search page for my andriod app using PHP,JSON and SQL.
here is the code that is giving me the error :
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
tempID += json_data.getString("ID") + "\n";
tempID += json_data.getString("heading") + "\n";
tempID += json_data.getString("rank") + "\n:";
}
arr = tempID.split(":");
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
}catch (Exception e){
String errMsg = "error when putting the json data in the list";
Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
}
i have already used this code on another page and it works perfectly but when using it another page/activity it gives me an error when trying to put the json data in listview.
i would guess the problem is when i am setting the ArrayAdapter, have i done anything wrong?
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
To answer your final question:
//array list
List<String> your_array_list = new ArrayList<String>();
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
your_array_list.add(json_data.getString("ID") + "\n");
your_array_list.add(json_data.getString("heading") + "\n");
your_array_list.add(json_data.getString("rank") + "\n:");
}
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,your_array_list));
//then, to get the items from inside the adapter:
for(String item_in_list : your_array_list){
System.out.println(item_in_list);
}
To answer the original question:
Check out http://jsonformatter.curiousconcept.com/ for formatting issues
Try looking at this info:
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
FYI: The inbuilt JSONObject and JSONArray cannot be used to get certain json responses.
You could try downloading a small library named "json-simple-1.1.1.jar" from this link https://json-simple.googlecode.com/files/json-simple-1.1.1.jar.
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);
}