how to get this output in java - 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);

Related

How to display the suggested word in textView based on the selected code from spinner?

I have this lookup json where it display suggested word. If I input "T" in the editText all values that has "t" in its word will display in the suggested list.
It's already implemented.
what I wanted to do is, if I select a code in spinner, the suggested display value will be based on the selected code.
Here is my json for my spinner
{
"products"{
"BI-BIKE",
"CA-CAR",
"MO-MOTOR",
"TR-TRICYCLE"
}
}
Here is my json for lookupjson
{
"BI": {
"brand": {
"GNT": "GIANT",
"TRL": "TREK",
"CNN": "CDALE",
"STC": "SANTA",
}
},
"CA": {
"brand": {
"AIC": "AICHI",
"BRI": "BRIGDESTONE",
"CON": "CONTINENTAL",
"DUN": "DUNLOP",
}
},
"MO": {
"brand": {
"CAN": "CANON",
"CAS": "CIO",
"FUJ": "FUJ",
"GPR": "PRO",
}
}
}
What I need to do is
If I select "BI" , and I type "T" in the editText field, all values from "BI" code with "t" will display.
first I need to get the first word before the (-) for me to check the code After getting the code check first the code before displaying suggested words.
here is the code where I display the suggested values without the connection from the selected in spinner.
private void loadLookupCategoryJson() {
mLookupProducts = new ArrayList<>();
mArrayStringLookupProduct = new ArrayList<String>();
try {
JSONObject json = new JSONObject(loadLookupBrandJSON());
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject obj = (JSONObject) json.get(key);
JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
JSONObject desc = obj.getJSONObject(Keys.CATEGORY_DESC);
final String productCode = mProductDescriptionCd.split("-")[0];
if (productCode.equals(brand)){
Iterator<String> brandKeys = brand.keys();
while (brandKeys.hasNext()) {
String bKey = brandKeys.next();
mArrayStringLookupProduct.add((String) brand.get(bKey));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Expected Result
Selected Products: BI-BIKE
Inputted text from TextField: T
Display suggested word:
GIANT
TREK
SANTA
Actual Result
Selected Products: BI-BIKE
Inputted text from TextField: T
Display suggested word:
GIANT
TREK
SANTA
BRIGDESTONE
CONTINENTAL

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\""

how i can change value of field of a string (format json)?

I'm developing a web services in java.
In the service I have to check the value of the 'desagg' field if it is equal to 0 I do not have to do anything while if it is greater than 0 I have to make another query and put the result in place of the value of the 'desArticle' field inside the json
I try to use gson method of google library but i don't think is the right method
String sql="SELECT sigdoc as sigla, numdoc as numero, datdoc as data , procor AS seq_articolo, desagg , precorpo.codint as codiceInterno, qtauni AS quantitaArticolo, " +
" przuni AS prezzoVendita, (scont0/100) AS sconto1, (scont1/100) AS sconto2, (scont2/100) AS sconto3, impnet AS importoNetto, datcon as dataConsegna, serdoc as chiaveRiga," +
" coarfo as codiceArticolo, descri as desArticolo" +
" FROM precorpo " +
" INNER JOIN anamagge ON precorpo.codint=anamagge.codint " +
" WHERE tiprig=0 AND sigdoc='"+sigdoc+"' AND numdoc="+numdoc+"" +
" ORDER BY procor;";
try
{
json = db.executeQueryTOJSON2(sql);
JsonObject jobj = new Gson().fromJson(json, JsonObject.class);
int result = jobj.get("desagg").getAsInt();
if (result > 0)
{
String query2=" select group_concat(descri) from memodocu where pointm="+result+" group by pointm;";
ResultSet rs = db.executeQuery(query2);
while(rs.next())
{
String desc = rs.getString("group_concat(descri)");
}
}
}
catch(Exception e)
{
System.out.println("errore "+e);
}
json in output is:
[ { "sigla":"PREV" , "numero":1.1000122E7 , "data":"" , "seq_articolo":1 , "desagg":0 , "codiceInterno":25951 , "quantitaArticolo":2.0 , "prezzoVendita":4.62 , "sconto1":0.0000 , "sconto2":0.0000 , "sconto3":0.0000 , "importoNetto":9.24 , "dataConsegna":"" , "chiaveRiga":7379 , "codiceArticolo":"A025951" , "desArticolo":"025951 ARTICOLO DI PROVA" } , { "sigla":"PREV" , "numero":1.1000122E7 , "data":"" , "seq_articolo":2 , "desagg":100 , "codiceInterno":15879 , "quantitaArticolo":20.0 , "prezzoVendita":2.17 , "sconto1":0.0000 , "sconto2":0.0000 , "sconto3":0.0000 , "importoNetto":43.4 , "dataConsegna":"" , "chiaveRiga":7380 , "codiceArticolo":"A015879" , "desArticolo":"I want to modify this" } ]
I'm a beginner with json
Gson is the right way to go, according the doc you can parse the string and then gey a type-value by a given key
here the doc:
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonElement.html#getAsInt--
JsonObject jobj = new Gson().fromJson(mySqlResultAsJson, JsonObject.class);
int result = jobj.get("desagg").getAsInt();
if (result >= 0)
{
do another request
}
If you want parse this :
{ "sigla":"PREV" , "numero":1.1000122E7 , "data":"" , "seq_articolo":2 , "desagg":100 , "codiceInterno":15879 , "quantitaArticolo":20.0 , "prezzoVendita":2.17 , "sconto1":0.0000 , "sconto2":0.0000 , "sconto3":0.0000 , "importoNetto":43.4 , "dataConsegna":"" , "chiaveRiga":7380 , "codiceArticolo":"A015879" , "desArticolo":"I want to modify this" }
You might do somthing like ;
MyObject myObj = new Gson().fromJson(myJsonStream, MyObject.class);
int desagg = myObj.getDesagg();
And define an object like this :
class MyObject {
private String sigla;
private float numero;
private String data;
...
}
I solved the problem!
JSONArray jsonarray = new JSONArray(json);
for (int i = 0; i < jsonarray.length(); i++)
{
JSONObject jsonobject = jsonarray.getJSONObject(i);
String tmp = jsonobject.getString("desagg");
if(!tmp.equals("0"))//vuol dire che dessagg diverso da 0
{
String sql2="select group_concat(descri) from memodocu where pointm="+tmp+" group by pointm;";
ResultSet rs = db.executeQuery(sql2);
String tmp2="";
while(rs.next())
{
tmp2=rs.getString("group_concat(descri)");
}
jsonobject.put("desArticolo", tmp2);
}
I used the jsonArray to parse json string and json object to get the value of the field I wanted then if tmp is different from 0 I go to run the query I take the result and update the value of the field desArticle
the final result will end up on the jsonarray variable, to print it you have to do jsonarray.toString ();

JSON Array Parsing multiple array

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();
}

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);
}

Categories

Resources