Gson to get Json value for a pie chart using Highcharts - java

I am working on Pie Charts using HighCharts.
The structure of JSON i needed is
data: [
['Firefox', 45.0],
['IE', 26.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
I am using GSON to convert this into JSON object.
I tried to add a class 'Browser' which contains
private List browserName = new ArrayList();
private List browserValue = new ArrayList();
// passing the browser class object to Gson
gson.toJson(browser);
In graph I passed the data as
data: [
json.browserName,json.browserValue
]
But this didnt worked. How can I achieve the required JSON format when name and value is a list.

I added some quotes and braces to make your json valid. Then, it's a matter of looping through your data key which gives you an array of arrays.
String jsonString =
"{'data':[['Firefox',45.0],['IE',26.8],['Safari',8.5],['Opera',6.2],['Others',0.7]]}";
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray data = jsonObject.get("data").getAsJsonArray();
for(int i = 0; i < data.size(); i++) {
JsonArray dataIndex = data.get(i).getAsJsonArray();
System.out.println(dataIndex.get(0));
System.out.println(dataIndex.get(1));
}
I find it helps me to visualize the json before writing code to go in and get values.

Related

Iterate through a collection of JSON Objects

I have a JSON file called mani.json which contains several objects, each object containing 3 key-value pairs that have information about some artifact files.
{ "art_src_path": "source/subdir/hi-there.txt","art_id": "6945-L9.txt","art_date": "2018:03:10 01:10:33"}
{ "art_src_path": "source/hello-world.txt","art_id": "10426-L13.txt","art_date": "2018:03:10 01:10:33"}
{ "art_src_path": "source/subdir/testfile.txt","art_id": "50518-L66.txt","art_date": "2018:03:10 01:10:33"}
I want to iterate through each of these objects in another file called FileTest.java and get the value corresponding to art_src_path. My FileTest.java file contains code that looks like this:
<!-- language: java -->
JSONParser parser = new JSONParser();
JSONObject a = (JSONObject) parser.parse(new FileReader("mani.json"));
for (Object o : a ) {
String path = (String) o.get("art_src_path");
File myFile = new File(path);
System.out.println("Source path: "+path);
}
NetBeans prompts an error and states that the object returned by the parser is not iterable and so I cannot use the for-each loop.
While this code, with certain modifications, worked well for iterating through an array of objects, it seems to fail for iterating through an object of objects.
So I have 2 questions:
What does the parser return; so that it is iterable for an array but not for an object?
How can I iterate through all the objects in mani.json to get the value for art_src_path from each object?
Almost all the answer so far tell me how to iterate over an array of objects. I am able to do that. I need to know how to iterate over an object of objects.
Thank you.
Is mani.json file is correctly json format? If so, the list would be JSONArray. JSONArray can iterate but JSONObject cannot.
If mani.json file is not json format but just text file. read line by line and parse each as JSONObject.
String strJson = "[{ \"art_src_path\": \"source/subdir/hi-there.txt\",\"art_id\": \"6945-L9.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/hello-world.txt\",\"art_id\": \"10426-L13.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/subdir/testfile.txt\",\"art_id\": \"50518-L66.txt\",\"art_date\": \"2018:03:10 01:10:33\"}]" ;
System.out.println("input = "+strJson) ;
JSONParser parser = new JSONParser() ;
JSONArray a = (JSONArray) parser.parse(strJson) ;
for (Object o:a) {
String path = (String) ((JSONObject) o).get("art_src_path") ;
System.out.println("source path:"+path) ;
}

Get the count of entries from a json file

I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here.
I am not able to get the string value(json) for the code below:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
Please find below the entire code:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
JSON Sample:
{
"Department":
[
{"SectionId":"1","SectionName":"Childrens Wear"},
{"SectionId":"2","SectionName":"Womens Wear"},
{"SectionId":"3","SectionName":"F&A"},
{"SectionId":"1","SectionName":"Mens Wear"}
]
}
I am new to java as well as api's.
Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key.
JSONArray jsonArray = jsnobject.getJSONArray("Department");

Parsing multiple json objects in java

I have this json file that I'm trying to parse in my program.
{
"items": [{
"0": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
},
"1": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
}
}]
}
I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out.
Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
JSONObject jsonObject = (JSONObject) obj;
JSONArray items = (JSONArray) jsonObject.get("items");
for (int i = 0; i < items.size(); i++) {
JSONObject item = (JSONObject) items.get(i);
System.out.print(item.toString());
}
Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with).
What did you find troubling with GSON?
If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object.
Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);
Then you can call
JsonArray array = jsonFile.get("items").getAsJsonArray();
Then to grab the attributes from the first element of the array.
array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

simpleJson parsing in Java

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below
[{"styleId":94,
"status":"verified",
"abv":"4.2",
"name":"Bud Light"}]
Here is my current code
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
Long currPage = (Long)jsonObject.get("currentPage");
System.out.println(currPage);
JSONArray jArray = (JSONArray)jsonObject.get("data");
System.out.println(jArray);
inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.
Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop.
int resultSize = jArray.length();
JSONObject result;
for (int i = 0; i < resultSize; i++) {
result = resultsArray.getJSONObject(i);
String name = result.getString("name");
// do whatever you want to do now...
}
just use Gson . it works well out of the box with any object type you supply.
This is an example from the user's guide:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

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