JSON Array Parsing multiple array - java

i have this fragment of JSON code that i want to parse: basically i want to store the "effective time" and "purpose", that you can see inside the "results" json array using Java(Android Studio), but i'm struggling doing it as it's my first time dealing with JSON.
{
"results": [
{
"effective_time": "20121114",
"inactive_ingredient": [
"Inactive ingredients *acetylated monoglycerides, *anhydrous lactose, *carnauba wax, colloidal silicon dioxide,*corn starch, *croscarmellose sodium, D&C Yellow #10 Aluminum Lake, FD&C Yellow #6 Aluminum Lake, hypromellose, *hypromellose phthalate, *iron oxide Yellow (iron oxide ochre), methacrylic acid copolymer, microcrystalline cellulose, *mineral oil, *polyethylene glycol (PEG)-400, *polysorbate 80, povidone, pregelatinized starch, *propylene glycol, *simethicone, silicon dioxide, sodium bicarbonate, sodium hydroxide, sodium lauryl sulfate, starch, stearic acid, talc, titanium dioxide, triacetin, and triethyl citrate. *May also contain."
],
"purpose": [
"Purpose Pain reliever"
],
"keep_out_of_reach_of_children": [
"Keep out of reach of children In case of overdose, get medical help or contact a Poison Control Center right away."
]
...
...
}
]
}
this is my code so far
String drugDescription="no description";
try{
JSONObject jsonQueryResult = new JSONObject(JSONFILE);
JSONArray jsonResultArray = jsonQueryResult.getJSONArray("result");
JSONObject jsonDrugDescription = jsonResultArray.getJSONObject(0);
drugDescription = jsonDrugDescription.toString();
}
catch(JSONException e){
e.printStackTrace();
}
searchResultTextView.setText(drugDescription);
drugDescription is still showing "no description"
thank you for the help!

If you are new you should go through some tutorial on Json parsing here.
For getting the effective_time and purpose you can do as:
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray firstResult = jsonObject.getJSONArray("results");
if (firstResult != null && firstResult.length() > 0) {
for (int i=0; i<firstResult.length(); i++) {
JSONObject result = firstResult.getJSONObject(i);
// This is your effective_time;
String effective_time = result.getString("effective_time");
JSONArray purpose = result.getJSONArray("purpose");
if (purpose != null && purpose.length() > 0) {
for (int j=0; j<purpose.length(); j++) {
// This is the purpose;
String purposeData = purpose.getString(j);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

how to get this output in java

The code is:
public JSONArray tree_data() {
JSONArray result = new JSONArray();
JSONArray nodes = new JSONArray();
try {
String query= "select parent_names.name as parent_name, child_names.name as child_name, parent_child.title from parent_child INNER join parent_names on parent_names.id=parent_child.parent_id\r\n" +
" INNER join child_names on child_names.id=parent_child.child_id order by parent_names.name;";
Statement td = this.con.createStatement();
ResultSet rst=td.executeQuery(query);
String parent="";
int i=0;
while(rst.next())
{
JSONObject childs = new JSONObject();
JSONObject obj1 = new JSONObject();
String nowparent=rst.getString("parent_name");
if(parent.equals(nowparent)) {
childs.put("text",rst.getString("child_name"));
childs.put("title", rst.getString("title"));
nodes.put(childs);
}else {
parent=nowparent;
obj1.put("text", parent);
childs.put("text",rst.getString("child_name"));
childs.put("title", rst.getString("title"));
nodes.put(childs);
}obj1.put("nodes", nodes);
result.put(obj1);
}
}
catch (Exception e) {
System.out.print(e);
}
System.out.print(result);
return result;
}
I want this JSON Output
[
{
text: 'Order',
nodes: [
{
text: 'countrywise',
title: 'sss'
},
{
text: 'factorywise',
title: 'ffff'
}
]
},
{
text: 'sales',
nodes: [
{
text: 'countrywise',
title: 'sss'
},
{
text: 'factorywise',
title: 'ffff'
},
{
text: 'Season',
title: 'eeee'
}
]
}
];
This is the database.
parent_name child_name title
Order,
Seoson,
sss, / /
Order, Customer,
ccc, //
Slaes,
Season,
sssss, //
Slaes,
Customer,
ssssds, //
Slaes,
country,
sssdsds
more ways are using but I can't solved it. I think problems have a loop but not showing what is the problem in this loop. please help this solve this question. thank you
correct some codes. now working
JSONObject childs = new JSONObject();
JSONObject obj1 = new JSONObject();
String nowparent=rst.getString("parent_name");
if(parent.equals(nowparent)) {
childs.put("parent",rst.getString("child_name"));
childs.put("title", rst.getString("title"));
nodes.put(childs);
}else {
nodes=new JSONArray();
obj1.put("nodes", nodes);
parent=nowparent;
obj1.put("parent", nowparent);
childs.put("parent",rst.getString("child_name"));
childs.put("title", rst.getString("title"));
nodes.put(childs);
result.put(obj1);

Gson parser crashes due to blank character

I have a file in JSON format. Gson parser crashes when it encounters a blank in it, as in State = "West Virginia", but it can parse "West-Virginia" where the blank character is replaced. I am using BufferedReader in Java.
But if I pass the same string hard-coded, the parser works.
import java.io.* ;
import com.google.gson.*;
public class gson_test {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
BufferedReader br2 = null ;
String jsonStr = "[{month = august, weather:clear}, [333] , {addr : {place = {city = city_name, county : its_name}, state = \"West Virginia\" } } ]" ;
// System.out.printf("json-str : %s \n", jsonStr);
GsonParseStr(jsonStr, (JsonElement) null );
try {
String file2read_json = "c:\\enter\\filename\\here";
br2 = new BufferedReader(new FileReader(file2read_json));
// https://sites.google.com/site/gson/gson-user-guide#TOC-Array-Examples
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
Object obj2 = gson.fromJson(br2, Object.class); // parses json-str into an object
GsonParseStr(obj2.toString(), (JsonElement) null );
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br2 != null) {
br2.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static void GsonParseStr(String jsonStr, JsonElement elem) {
JsonParser parser2 = new JsonParser();
elem = parser2.parse(jsonStr); // this stmt crashes for the blank char
System.out.printf("parse str : %s \n", jsonStr);
}
}
My file's content is:
[{month = august, weather:clear}, [333] , {addr : {place = {city = city_name, county : its_name}, state = "West.Virginia" } } ]
If I change "West.Virginia" to "West Virginia" the program crashes.
The file should get parsed the same way as 'file-contents in the form of raw string'.
PS : As suggested by JPinzon, I need quotes around (West Virginia) in the file, which I did have. But they have to be further escaped. Thus : (State: "West Virginia") won't do; it should be (State: "\"West Virginia\""). Optionally, the key 'State' can have double-quotes around it, but that is optional.
Try fixing your JSON to this:
[{"month":"august", "weather":"clear"}, [333], {"addr":{"place":{"city":"city_name", "county":"its_name"}, "state":"West Virginia"}}]
... or nicely formatted:
[
{
"month":"august",
"weather":"clear"
},
[
333
],
{
"addr":{
"place":{
"city":"city_name",
"county":"its_name"
},
"state":"West Virginia"
}
}
]
If you debug, you will see that the string obj2.toString() doesn't contain quotes around "West Virginia" because the gson.fromJson(br2, Object.class) has removed them while parsing. That's why it crashes.
To avoid this error you can try adding escaped quotes in your file like this state = "\"West Virginia\""

Json parsing: Iterating through the values?

I'm trying to use json.simple to get things from this json file:
"Main": {
"Part1":{
"Length": 2,
"Flags": 2,
"Sequence": 4
},
"Part2":{
"Length": 2,
"Type":2,
"Main_Dest":4,
"Main_Source":4,
"Sequence":4,
"Data": {
"1":12,
"2":24
},
"Blank": 8
}
}
Basically, I want to reach the "Type" value in Part2, and on the way add all values. Meaning in the end I want to have the sum 10 (length+flags+sequence+length) and the number 2 for the value "Type". My main problem here is that I have to do it generically, so I can't just collect the values by name because they might change or additional values could be added. Only the value "Type" will always be called exactly that.
What I've done so far is this:
private static void parseJson() {
String path = "...config.json";
boolean count = false;
int sum = 0;
try {
FileReader reader = new FileReader(path);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObject.entrySet();
JSONObject main = (JSONObject) jsonObject.get("Main");
for (Iterator iterator = main.keySet().iterator(); iterator.hasNext();){
String key = (String) iterator.next();
//this is where I'm stumped. Do I keep going into the JSONObject until I get to a value?
if (count){
sum += (int) sahara.get(key);
}
if (key.equals("Type")){
count = true;
}
}
System.out.println(skip);
} catch (Exception e) {
}
}
Obviously I don't really know what I'm doing with this. How do I iterate the lowest level in the json file?
As a little side question, which Json parser libraries should I use if I might sell my software? In other words, which doesn't cause licensing issues?
You can iterate over keys recursively, but you can't calculate sum, result will be unpredictable.
jsonObject.keySet not guarantee returns the keys in the same order as they appears in file.
Use the stream API for Json.
I have added the missing curly braces to fix your input.
{
"Main": {
"Part1":{
"Length": 2,
"Flags": 2,
"Sequence": 4
},
"Part2":{
"Length": 2,
"Type":2,
"Main_Dest":4,
"Main_Source":4,
"Sequence":4,
"Data": {
"1":12,
"2":24
},
"Blank": 8
}
}
}
This examples shows how to use the stream API.
// -*- compile-command: "javac -cp javax.json-1.0.jar q43737601.java && java -cp .:javax.json-1.0.jar q43737601"; -*-
import java.io.FileReader;
import javax.json.Json;
import javax.json.stream.JsonParser;
class q43737601
{
public static void main (String argv[]) throws Exception
{
String path = "config.json";
int sum = 0;
JsonParser p = Json.createParser (new FileReader (path));
while (p.hasNext()) {
JsonParser.Event e = p.next();
switch (e) {
case VALUE_NUMBER:
sum += Integer.parseInt(p.getString());
break;
case KEY_NAME:
if ("Type".equals(p.getString()))
System.out.println(sum);
break;
}
}
}
}
If you run it, it displays 10. The example sums up all numbers up to a key called "Type".
I tried the above example with OpenJDK. It was necessary to follow the steps explained in this answer. I had to set the class path (-cp) in the compile command.

Split List View Into sections by using the below given json response [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 7 years ago.
I have a json response like below
{
"continent":"Africa",
"name":"Djezzy",
"cid":"3",
"country":"Algeria",
"filename":"djezzy.png",
"iso2":"DZ",
"iso3":"DZA",
"network":"OTA NET, ALG 02, 603 02"
},
{
"continent":"Africa",
"name":"Etisalat Nigeria",
"cid":"156",
"country":"Nigeria",
"filename":"etisalat.png",
"iso2":"NG",
"iso3":"NGA",
"network":"Etisalat"
},
{ },
{
"continent":"Americas",
"name":"Tigo",
"cid":"47",
"country":"Colombia",
"filename":"tigo.png",
"iso2":"CO",
"iso3":"COL",
"network":"Tigo"
},
{
"continent":"Europe",
"name":"Beeline-Armenia",
"cid":"11",
"country":"Armenia",
"filename":"beeline.png",
"iso2":"AM",
"iso3":"ARM",
"network":"Beeline, ArmenTel, ARMGSM, ARM 01, 283 01"
},
{
"continent":"Europe",
"name":"life",
"cid":"220",
"country":"Ukraine",
"filename":"life.png",
"iso2":"UA",
"iso3":"UKR",
"network":"UA Astelit, UKR 06, 255 06"
},
{
"continent":"Europe",
"name":"T-Mobile",
"cid":"240",
"country":"Montenegro",
"filename":"tmobile.png",
"iso2":"ME",
"iso3":"MNE",
"network":"T-Mobile CG, YU 04, 220 04, 297 02, MNE 02"
},
{
"continent":"Europe",
"name":"Turkcell",
"cid":"215",
"country":"Turkey",
"filename":"turkcell.png",
"iso2":"TR",
"iso3":"TUR",
"network":"Turkcell"
},
{
"continent":"Middle East & Asia",
"name":"3hk",
"cid":"96",
"country":"Hong Kong",
"filename":"3hk.png",
"iso2":"HK",
"iso3":"HKG",
"network":"3, 3G, Orange, 3-Dualband"
}
Now I have a requirement to display the list of countries and divide the list into continent wise sections. I can use Expandable List View but how can I divide this json into multiple array lists which I could then use as group and child in expandable list view.
For better undertanding I need to display the data like this... https://drive.google.com/a/panzertechnologies.net/file/d/0B7Jo72tgHOJUVjVLS0cwVWhaUzQ/view?usp=sharing
Thanks in advance.
try like this , it May help you
initilaize the string array
String[] CENTERNAME,CENTER_ID;
initialize the arraylist before getting json array
//Converting string to Array list
ArrayList<String> centername_arr= new ArrayList<String>();
ArrayList<String> Center_Id_arr= new ArrayList<String>();
if ((response.toString()).contains("{"))
{
// JSONArray jr = new JSONArray(response);
SoapObject rep = (SoapObject) envelope.bodyIn;
JSONArray jr = new JSONArray(rep.getPropertyAsString(0));
for (int i = 0; i < jr.length(); i++)
{
JSONObject jb = (JSONObject) jr.get(i);
Center_id = jb.getString("CenterId");
CenterName = jb.getString("CenterName");
centername_arr.add(CenterName);
Center_Id_arr.add(Center_id);
}}
//Convert Arraylist to String Array
CENTERNAME = new String[centername_arr.size()];
CENTERNAME = centername_arr.toArray(CENTERNAME);
CENTER_ID= new String[Center_Id_arr.size()];
CENTER_ID = Center_Id_arr.toArray(CENTER_ID);
Then You Can use the String Array in your Listview
Thank you all for spending some time on reading my question.. I found the answer and below is the solution.
JSONObject j=jo.getJSONObject("response");
JSONArray jar=j.getJSONArray("data");
for (int i = 0; i < jar.length(); i++) {
JSONObject job=jar.getJSONObject(i);
String continent=job.getString("continent");
String name=job.getString("name");
String country=job.getString("country");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
boolean exists = false;
for (HashMap<String, String> hashMap : contactList) {
try {
if (hashMap.get("continent").equals(continent)) {
exists = true;
break;
}
} catch (Exception e) {
}
}
if (!exists) {
contact.put("continent", continent);
}
contact.put("name", name);
contact.put("country", country);
contactList.add(contact);
}

Null Pointer Exception JsonArray Size

While retrieving objects from a Json file for an Android App, I am getting a NullPointerException when I try to access to the size of a Json Array.
Here is one Json Object of the "results" array:
results: [
{
aliases: null,
api_detail_url: "http://www.giantbomb.com/api/game/3030-26559/",
date_added: "2009-05-22 10:03:31",
date_last_updated: "2014-01-14 08:27:36",
deck: "All three Metroid Prime titles in one package. Metroid Prime and Metroid Prime 2: Echoes are reworked to include 480p widescreen, motion controls, and achievements.",
description: "<h2>Overview</h2><p style="">Metroid Prime Trilogy is a single-disc compilation for the <a data-ref-id="3045-36" href="/wii/3045-36/" slug="wii">Nintendo Wii</a> consisting of <a data-ref-id="3030-15473" href="/metroid-prime/3030-15473/" slug="metroid-prime">Metroid Prime</a>, <a data-ref-id="3030-1597" href="/metroid-prime-2-echoes/3030-1597/" slug="metroid-prime-2-echoes">Metroid Prime 2: Echoes</a>, and <a data-ref-id="3030-4725" href="/metroid-prime-3-corruption/3030-4725/" slug="metroid-prime-3-corruption">Metroid Prime 3: Corruption</a>. The first two games in the series, originally released for the <a data-ref-id="3045-23" href="/gamecube/3045-23/" slug="gamecube">Nintendo GameCube</a>, have been updated with 480p widescreen support, improved graphic effects, and motion controls similar to those found in Metroid Prime 3.",
expected_release_day: null,
expected_release_month: null,
expected_release_quarter: null,
expected_release_year: null,
id: 26559,
image: {},
name: "Metroid Prime Trilogy",
number_of_user_reviews: 3,
original_game_rating: [],
original_release_date: "2009-08-24 00:00:00",
platforms: [
{
api_detail_url: "http://www.giantbomb.com/api/platform/3045-36/",
id: 36,
name: "Wii",
site_detail_url: "http://www.giantbomb.com/wii/3045-36/",
abbreviation: "WII"
}
],
site_detail_url: "http://www.giantbomb.com/metroid-prime-trilogy/3030-26559/",
resource_type: "game"
}
I'm trying to get the size of "platforms", just because a game can be played, for example, both on PC and MAC:
if (response != null && response.length() > 0) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Response: "
+ response);
JsonObject jsonObject = (JsonObject) parser.parse(response);
JsonArray items = jsonObject.getAsJsonArray("results");
String id = null;
String title = null;
String thumbnail = null;
String description = null;
String image = null;
String platform = null;
//ArrayList<String> platform = new ArrayList<String>();
for (int index = 0; index < items.size(); index++) {
JsonObject itemObj = (JsonObject) items.get(index);
id = itemObj.get("id").getAsString();
title = itemObj.get("name").getAsString();
thumbnail = ((JsonObject)itemObj.get("image")).
get("tiny_url").getAsString();
image = ((JsonObject)itemObj.get("image")).
get("small_url").getAsString();
description = itemObj.get("deck").getAsString();
JsonArray platforms = jsonObject.getAsJsonArray("platforms");
Log.d(com.example.ludos2_0.MainActivity.TAG,
title);
for (int j = 0; j < platforms.size(); j++) {
JsonObject platformObj = (JsonObject) platforms.get(j);
platform = platformObj.get("name").getAsString();
videogamesList.add(new Videogame(id, title,
thumbnail, image, description, platform));
Log.d(com.example.ludos2_0.MainActivity.TAG,
title + " " + platform);
}
}
But I get a NullPointerException at the line of the 'platforms.size()'.
What am I doing wrong?
Thanks in advance and sorry for my English, I'm italian!
You are not getting values here
JsonArray platforms = jsonObject.getAsJsonArray("platforms");
platforms is null, thats why you are gettin that exception
Update:
I have realized you have a problem here:
JsonArray platforms = jsonObject.getAsJsonArray("platforms");
change to:
JsonArray platforms = itemObj.getAsJsonArray("platforms");
Make sure you are getting an object within platforms handler. Try this :
JsonArray platforms = jsonObject.getAsJsonArray("platforms");
You should get platforms from results not from your main object
JsonArray platforms = jsonObject.getAsJsonArray("platforms"); //WRONG
JsonArray platforms = itemObj.getAsJsonArray("platforms"); //GOOD

Categories

Resources