I m using highcharts.js for my project What I'm trying to do is format my tool tip. I have written a java method which is returning me the output in the json format as
syList:
[{
"value1": "Some Area",
"value2": "1",
"agrAcronym": "AB"
}, {
"value1": "Some AREA",
"value2": "2",
"agrAcronym": "BA"
}, {
"value1": "Some Area",
"value2": "3",
"agrAcronym": "NA"
}, {
"value1": "Some Area",
"value2": "4",
"agrAcronym": "MW"
}, {
"value1": "Some Area",
"value2": "5",
"agrAcronym": "PW"
}, {
"value1": "Some Area",
"value2": "6",
"agrAcronym": "NP"
}, {
"value1": "Some Area",
"value2": "7",
"agrAcronym": "SP"
}, {
"value1": "Some Area",
"value2": "8",
"agrAcronym": "MS"
}, {
"value1": "Some Area",
"value2": "9",
"agrAcronym": "SA"
}],
my chart script is
var options2 = {
chart : {
renderTo : 'outgoingContainer',
type : 'column',
marginTop: 50,
},
title : {
text : 'Something Area',
style: {
color : '#2B1B17',
fontWeight: 'bold'
}
},
xAxis : {
title : {
text : null
},
labels: {
y: 30,
}
},
yAxis : {
title : {
text : 'something',
align : 'middle'
},
stackLabels : {
enabled : true,
style : {
fontWeight : 'bold',
color : (Highcharts.theme && Highcharts.theme.textColor)
|| 'charcoal'
},
formatter : function() {
return getCurrencyFormat(parseInt(this.total));
}
}
},
tooltip : {
formatter : function() {
return '' + this.x + ': ' + getCurrencyFormat(parseInt(this.y));
}
},
plotOptions : {
series: {
borderWidth: 1,
borderColor: 'black'
},
column : {
stacking : 'normal',
dataLabels : {
enabled : false,
color : (Highcharts.theme && Highcharts.theme.dataLabelsColor)
|| 'black',
style : {
fontWeight : 'bold',
}
}
}
},
legend : {
enabled : false
},
credits : {
enabled : false
},
series : [ {
color : '#00FFFF',
} ]
};
$.getJSON(
function(data) {
options2.xAxis.categories = [];
options2.series[0].data = [];
if (data["syList"] != null)
{
$.each(data["syList"], function( index, value ) {
options2.xAxis.categories[index] = data["syList"][index] ["value1"];
options2.series[0].data[index] = parseFloat(data["syList"][index]["value2"]);
});
$("#outgoingContainer").show();
} else {
options2.yAxis.title.text = "";
$("#outgoingContainer").hide();
}
new Highcharts.Chart(options2);
});
You need to set useHtml = true on your tooltip and this will allow you to format your tooltip any way that you want. Make sure that the data for your series is set to syList and set the headerFormat, pointFormat, and footerFormat on your tooltip like this. Note the {point.agrAcronym}.
tooltip: {
shared: true,
useHTML: true,
headerFormat: '<table>',
pointFormat: '<tr><td style="color: {series.color};">{series.name}: </td>' +
'<td>{point.agrAcronym}</td></tr>',
footerFormat: '</table>'
},
series: [{
data: syList
}]
Related
I have made a page allowing to see tools arranged in classes and subclasses (3rd floor).
The tools database is on a server, and I receive the data as JSON.
Everything was working fine until I added a number of tools (and therefore classes)
My tools appear several times without reason in classes that are not the right ones.
I checked the JSON, no problem.
Here are screenshots of the problem and the code that allows me to retrieve the data and send it to my adapter.
Thanks for your help.
Random display problem image 1
Random display problem image 2
Random display problem image 3
ArrayList<String> famille1 = new ArrayList<>();
ArrayList<String> typeliste = new ArrayList<>();
HashMap<String, HashMap<String, HashMap<String, ArrayList<MatosItem>>>> ma = new HashMap<>();
ArrayList<String> materiauliste = new ArrayList<>();
HashMap<String, HashMap<String, HashMap<String, ArrayList<MatosItem>>>> materielsItemList = new HashMap<>();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
FetchData fetchData = new FetchData("http://" + adresseIp.getAdresseIP() + "/jsonmateriels.php");
if (fetchData.startFetch()) {
if (fetchData.onComplete()) {
String json = fetchData.getResult();
try {
HashMap<String, HashMap<String, ArrayList<MatosItem>>> typeItemList = new HashMap<>();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArrayOutils = jsonObject.getJSONArray("Outils");
for (int j = 0; j < jsonArrayOutils.length(); j++) {
HashMap<String, HashMap<String, ArrayList<MatosItem>>> typeItemList1 = new HashMap<>();
JSONObject fam = jsonArrayOutils.getJSONObject(j);
String famille = fam.names().getString(0);//permet d'avoir les choses contenu dans la classe soudeurs
JSONArray jsonArrayFamille = fam.getJSONArray(famille);//permet de récupérer le suivant
famille1.add(famille);
for (int i = 0; i < jsonArrayFamille.length(); i++) {
HashMap<String, ArrayList<MatosItem>> matItemList = new HashMap<>();
JSONObject typ = jsonArrayFamille.getJSONObject(i);
String type = typ.names().getString(0);
JSONArray jsonArrayType = typ.getJSONArray(type);
typeliste.add(type);
for (int k = 0; k < jsonArrayType.length(); k++) {
JSONObject mat = jsonArrayType.getJSONObject(k);
ArrayList<MatosItem> outils = new ArrayList<>();
String materiau = mat.names().getString(0);
JSONArray jsonArraylistout = mat.getJSONArray(materiau);
materiauliste.add(materiau);
for (int l = 0; l < jsonArraylistout.length(); l++) {
JSONObject out = jsonArraylistout.getJSONObject(l);
String description = out.getString("description");
String id = out.getString("id");
String ref = out.getString("ref");
String code_fourn = out.getString("code_fourn");
Log.e("boucle",description+id);
outils.add(new MatosItem(description, id, false, ref, code_fourn));
}
matItemList.put(materiau, outils);
}
typeItemList1.put(type, matItemList);
}
materielsItemList.put(famille, typeItemList1);
tabLayout.addTab(tabLayout.newTab().setText(famille));
}
ArrayList<String> list = new ArrayList<>();
for (String i : Objects.requireNonNull(materielsItemList.get(famille1.get(0))).keySet()) {
list.add(i);
Log.e(TAG, "run: "+i );
}
typeItemList = materielsItemList.get(famille1.get(0));
Log.e(TAG, "run: "+typeItemList );
matosListView.setAdapter(new MatosItemAdapter(context, typeItemList,list ));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
Fragment fragment = null;
if (tab.isSelected()) {
ArrayList<String> list = new ArrayList<>();
for (String i : Objects.requireNonNull(materielsItemList.get(famille1.get(tab.getPosition()))).keySet()) {
list.add(i);
}
HashMap<String, HashMap<String, ArrayList<MatosItem>>> typeItemList1 = new HashMap<>();
typeItemList1 = materielsItemList.get(famille1.get(tab.getPosition()));
matosListView.setAdapter(new MatosItemAdapter(context, typeItemList1, list));
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
progressBar.setVisibility(GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
I checked the JSON
I tried to use a thread
{
"Outils" : [{
"Soudeurs" : [
{
"Fils" : [
{
"Fil" : [
{
"description" : "Fil MIG G3SI1 diam 1.2",
"id" : "26",
"ref" : "bobine de 15 kg",
"code_fourn" : "x"
},
{
"description" : "Fourre OK1413 diam 1.2",
"id" : "45",
"ref" : "bobine 16 kg avec gaz",
"code_fourn" : "x"
},
{
"description" : "MIG inox 316L SI diam 1.2",
"id" : "46",
"ref" : "bobine 15 kg",
"code_fourn" : "x"
}]
}]
},
{
"Materiel de soudure" : [
{
"Gaine guide" : [
{
"description" : "fil 25 x 45 4M diam 1.2",
"id" : "27",
"ref" : "x",
"code_fourn" : "x"
}
]},
{
"Batterie" : [
{
"description" : "Warrior AIR ESAB",
"id" : "47",
"ref" : "x",
"code_fourn" : "x"
}
]},
{
"Cagoule" : [
{
"description" : "Couvre nuque noire ESAB",
"id" : "48",
"ref" : "x",
"code_fourn" : "x"
}
]},
{
"Protection" : [
{
"description" : "Ecran de protection bleu",
"id" : "49",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Visiere transparente pour ecran HG930B",
"id" : "50",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Visiere teinte pour ecran HG930B",
"id" : "51",
"ref" : "x",
"code_fourn" : "x"
}
]},
{
"Pince" : [
{
"description" : "Stubby original 400 A",
"id" : "52",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Masse bronze GCB 450 A",
"id" : "53",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Masse bronze GCB 600 A",
"id" : "54",
"ref" : "x",
"code_fourn" : "x"
}]
}]
},
{
"Electrodes" : [
{
"OK4627" : [
{
"description" : "Diam 2.5 x 350 rutile",
"id" : "25",
"ref" : "x",
"code_fourn" : "x"
}]
},
{
"OK4800" : [
{
"description" : "Diam 2.5 x 350",
"id" : "32",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Diam 3.2 x 350",
"id" : "33",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Diam 4 x 350",
"id" : "34",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Diam 5 x 450",
"id" : "35",
"ref" : "x",
"code_fourn" : "x"
}]
},
{
"Inox 316 L 17" : [
{
"description" : "Diam 2.5 x 300",
"id" : "36",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Diam 3.2 x 350",
"id" : "37",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "Diam 4 x 350",
"id" : "38",
"ref" : "x",
"code_fourn" : "x"
}]
},
{
"Gougeage" : [
{
"description" : "6 x 305",
"id" : "39",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "8 x 305",
"id" : "40",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "10 x 305",
"id" : "41",
"ref" : "x",
"code_fourn" : "x"
}]
},
{
"Nue" : [
{
"description" : "9.5 x 914 slice",
"id" : "42",
"ref" : "x",
"code_fourn" : "x"
}]
}]
}]},
{
"Ajusteurs" : [
{
"Accessoires" : [
{
"Nettoyant" : [
{
"description" : "26.5 kg alfa marine",
"id" : "44",
"ref" : "x",
"code_fourn" : "x"
}]
}]
},
{
"Hydraulique" : [
{
"Huile" : [
{
"description" : "Enerpac HF95Y bidon 5L",
"id" : "43",
"ref" : "x",
"code_fourn" : "x"
}]
}]
}]
},
{
"Machinistes" : [
{
"Accessoires" : [
{
"Lame ebavureur" : [
{
"description" : "E100S (longue) boite de 10",
"id" : "30",
"ref" : "x",
"code_fourn" : "x"
},
{
"description" : "B10S (courte) boite de 10",
"id" : "31",
"ref" : "x",
"code_fourn" : "x"
}]
}]
}]
}]
}
I would like to have a correct display of the tools and their class. I don't have to have expandables list
Hi working in Jolt transformation tool and getting know some in-depth details
Input
{
"characteristic": [
{
"name": "usageCharacteristicName",
"value": "availableBalance",
"#type": "usageCharacteristic",
"arrayIndex": "2"
},
{
"name": "usageCharacteristicValue",
"value": "2999.25",
"#type": "usageCharacteristic",
"arrayIndex": "2"
},
{
"name": "usageCharacteristicName",
"value": "Name",
"#type": "usageCharacteristic",
"arrayIndex": "0"
},
{
"name": "usageCharacteristicValue",
"value": "Jack",
"#type": "usageCharacteristic",
"arrayIndex": "0"
},
{
"name": "usageCharacteristicName",
"value": "Likes",
"#type": "usageCharacteristic",
"arrayIndex": "1"
},
{
"name": "usageCharacteristicValue",
"value": "Code",
"#type": "usageCharacteristic",
"arrayIndex": "1"
}
]
}
Jolt Spec :
[
{
"operation": "shift",
"spec": {
"characteristic": {
"*": {
"arrayIndex": {
"2": {
"#(2,value)": "data.queryBalance.accountBalance"
},
"0": {
"#(2,value)": "data.queryBalance.Name"
},
"1": {
"#(2,value)": "data.queryBalance.Likes"
},
}
}
}
}
}
]
Output :
{
"data" : {
"queryBalance" : {
"accountBalance" : [ "availableBalance", "2999.25" ],
"Name" : [ "Name", "Jack" ],
"Likes" : [ "Likes", "Code" ]
}
}
}
the Output i was getting is not good enough for me, want to do like String like bellow Expected.
Expected Output :
"availableBalance" : "2999.25",
"Name" : "Jack",
"Likes" : "Code"
how do i get like a String ?
I think this solve the problem
spec
[
{
//group keys and valeus for arrayIndex
"operation": "shift",
"spec": {
"characteristic": {
"*": {
"value": "newArray[#(1,arrayIndex)].#(1,name)"
}
}
}
},
{
//create a new object use a key and valeus matchs previous
"operation": "shift",
"spec": {
"newArray": {
"*": {
"usageCharacteristicValue": "#(1,usageCharacteristicName)"
}
}
}
}
]
output
{
"Name" : "Jack",
"Likes" : "Code",
"availableBalance" : "2999.25"
}
You need a modify transformation spec as well such as
[
{
// reduce to simple array "value" : [ "availableBalance", "2999.25" ] nested within an object
"operation": "shift",
"spec": {
"*": {
"*": {
"value": "&"
}
}
}
},
{
// combine components of the array so as to reform as a string
"operation": "modify-overwrite-beta",
"spec": {
"*": "=join(' : ',#(1,&))"
}
}
]
Edit: You can alternatively try the following for the new case :
[
{
// dissipate each array into different object with respect to arrayIndex values
"operation": "shift",
"spec": {
"*": {
"*": {
"value": "#(1,arrayIndex).&"
}
}
}
},
{
// combine components of each array colon-separatedly
"operation": "modify-overwrite-beta",
"spec": {
"*": {
"*": "=join(' : ',#(1,&))"
}
}
},
{
// convert to a unique array
"operation": "shift",
"spec": {
"*": {
"*": "&"
}
}
},
{
// combine components of each array comma-separatedly
"operation": "modify-overwrite-beta",
"spec": {
"*": "=join(' , ',#(1,value))"
}
}
]
I know how to do it by another library Josson. You may consider to use it.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(inputJSON);
Transform to an array of string
JsonNode node = josson.getNode(
"characteristic" +
".group(arrayIndex)" +
".concat(elements[name='usageCharacteristicName'].value" +
" ,' : '" +
" ,elements[name='usageCharacteristicValue'].value)");
System.out.println(node.toPrettyString());
Output
[ "availableBalance : 2999.25", "Name : Jack", "Likes : Code" ]
Transform to a single string
String str = josson.getString(
"characteristic" +
".group(arrayIndex)" +
".concat(elements[name='usageCharacteristicName'].value" +
" ,' : '" +
" ,elements[name='usageCharacteristicValue'].value)" +
".join(', ')");
System.out.println(str);
Output
availableBalance : 2999.25, Name : Jack, Likes : Code
Transform to a map
JsonNode node = josson.getNode(
"characteristic" +
".group(arrayIndex)" +
".map(elements[name='usageCharacteristicName'].value::elements[name='usageCharacteristicValue'].value)" +
".mergeObjects()");
System.out.println(node.toPrettyString());
Output
{
"availableBalance" : "2999.25",
"Name" : "Jack",
"Likes" : "Code"
}
Transform to a map with sorted "arrayIndex" as key
JsonNode node = josson.getNode(
"characteristic" +
".group(arrayIndex)" +
".sort(arrayIndex)" +
".map(arrayIndex.prepend('arrayIndex')::" +
" concat(elements[name='usageCharacteristicName'].value" +
" ,' : '" +
" ,elements[name='usageCharacteristicValue'].value))" +
".mergeObjects()");
System.out.println(node.toPrettyString());
Output
{
"arrayIndex0" : "Name : Jack",
"arrayIndex1" : "Likes : Code",
"arrayIndex2" : "availableBalance : 2999.25"
}
So I am incredibly new to Java and am needing help parsing a JSON response. I already have the method in which I am using to do so, but need help figuring out what exactly I am doing wrong.
I am using an API to retrieve recipes from a site. I am trying to get a list of recipes ("hits" in this case I assume?) that I can then show to the user.
Obviously I need the recipe name ("label" in this case) and other information. Can anyone help me?
Here is the response api response I am getting:
{
"q": "chicken",
"from": 0,
"to": 10,
"more": true,
"count": 168106,
"hits": [
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_b79327d05b8e5b838ad6cfd9576b30b6",
"label": "Chicken Vesuvio",
"image": "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg",
"source": "Serious Eats",
"url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
"shareAs": "http://www.edamam.com/recipe/chicken-vesuvio-b79327d05b8e5b838ad6cfd9576b30b6/chicken",
"yield": 4,
"dietLabels": [
"Low-Carb"
],
"healthLabels": [],
"cautions": [],
"ingredientLines": [
"1/2 cup olive oil",
"5 cloves garlic, peeled",
"2 large russet potatoes, peeled and cut into chunks",
"1 3-4 pound chicken, cut into 8 pieces (or 3 pound chicken legs)",
"3/4 cup white wine",
"3/4 cup chicken stock",
"3 tablespoons chopped parsley",
"1 tablespoon dried oregano",
"Salt and pepper",
"1 cup frozen peas, thawed"
],
"ingredients": [
{
"text": "1/2 cup olive oil",
"weight": 108
},
{
"text": "5 cloves garlic, peeled",
"weight": 15
},
{
"text": "2 large russet potatoes, peeled and cut into chunks",
"weight": 532.5
},
{
"text": "1 3-4 pound chicken, cut into 8 pieces (or 3 pound chicken legs)",
"weight": 1587.5732
},
{
"text": "3/4 cup white wine",
"weight": 169.5
},
{
"text": "3/4 cup chicken stock",
"weight": 180
},
{
"text": "3 tablespoons chopped parsley",
"weight": 11.4
},
{
"text": "1 tablespoon dried oregano",
"weight": 6
},
{
"text": "Salt and pepper",
"weight": 16.46384
},
{
"text": "Salt and pepper",
"weight": 8.23192
},
{
"text": "1 cup frozen peas, thawed",
"weight": 134
}
],
"calories": 4055.7632,
"totalWeight": 2765.59,
"totalTime": 60,
"totalNutrients": {},
"totalDaily": {},
"digest": []
},
"bookmarked": false,
"bought": false
},
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_8275bb28647abcedef0baaf2dcf34f8b",
"label": "Chicken Paprikash",
"image": "https://www.edamam.com/web-img/e12/e12b8c5581226d7639168f41d126f2ff.jpg",
"source": "No Recipes",
"url": "http://norecipes.com/recipe/chicken-paprikash/",
"shareAs": "http://www.edamam.com/recipe/chicken-paprikash-8275bb28647abcedef0baaf2dcf34f8b/chicken",
"yield": 4,
"dietLabels": [],
"healthLabels": [],
"cautions": [],
"ingredientLines": [],
"ingredients": [],
"calories": 3033.2012,
"totalWeight": 1824.6125,
"totalTime": 0,
"totalNutrients": {},
"totalDaily": {},
"digest": []
},
"bookmarked": false,
"bought": false
},
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_584ac5e486c088b3c8409c252d7f290c",
"label": "Chicken Gravy",
"image": "https://www.edamam.com/web-img/fd1/fd1afed1849c44f5185720394e363b4e.jpg",
"source": "Martha Stewart",
"url": "http://www.marthastewart.com/332664/chicken-gravy",
"shareAs": "http://www.edamam.com/recipe/chicken-gravy-584ac5e486c088b3c8409c252d7f290c/chicken",
"yield": 6,
"dietLabels": [],
"healthLabels": [],
"cautions": [],
"ingredientLines": [],
"ingredients": [],
"calories": 1092.3606,
"totalWeight": 1590.8628,
"totalTime": 270,
"totalNutrients": {},
"totalDaily": {},
"digest": []
},
"bookmarked": false,
"bought": false
},
{},
{},
{},
{},
{},
{},
{}
]
}
This is currently the method I am using to parse the JSON object:
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
getActivity().runOnUiThread(new Runnable() {
private Object Date;
#Override
public void run() {
String jsonData = myResponse;
query_result.setText(myResponse);
Log.d("response5", myResponse);
//JSONObject jsonData1 = new JSONObject(myResponse);
JSONObject Jobject = null;
try {
Jobject = new JSONObject(jsonData);
Log.d("jobject", Jobject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray Jarray = null;
try {
Jarray = Jobject.getJSONArray("hits");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object;
try {
object = Jarray.getJSONObject(i);
try {
JSONArray Recipe = object.getJSONArray("recipe");
}catch (JSONException e){
e.printStackTrace();
}
for (int j = 0; j < Jarray.length(); j++){
JSONObject object2 = null;
try {
object2 = Jarray.getJSONObject(j);
String Name = object2.getString("label");
String Photo = object2.getString("image");
Log.d("rec_query", " " + Photo);
}catch (JSONException e){
e.printStackTrace();
Log.d("response6:", e.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
});
return null;
}
}
NOTE THE {} {} are just different recipes...it wouldnt fit the whole response
At the moment, when I try to print my variables in the Log, I am getting a message that says the variable is empty (the variable that i used to store the different recipes/"hits".
Your response seems incomplete, it's not in the correct JSON format,Provide the right format and I'll try to help you
String s = "{\n" +
" \"a1\":\"1\",\n" +
" \"b2\":[\n" +
" {\n" +
" \"b21\":\"vb21\"\n" +
" },\n" +
" {\n" +
" \"b22\":\"vb22\"\n" +
" }\n" +
" ]\n" +
"}";
JSONObject object = JSON.parseObject(s);
String vb21 = object.getJSONArray("b2").getJSONObject(0).getString("b21");
like this,and neep to import com.alibaba.fastjson
But i dont`t know if you can use fastjson
I have multi Array key value string
For Example:
{
filters=[
{
eventConfig={
success=1.0,
bgColor=#27AE60,
successText=Yes
},
prid=9.0,
name=abc,
prqt=1.0,
price=199.89
},
{
eventConfig={
success=1.0,
bgColor=#27AE60,
successText=Yes
},
name=abc,
prid=10.0,
price=99.89,
prqt=1.0
},
{
eventConfig={
success=0.0,
bgColor=#C0392B,
successText=No
},
name=internet,
prid=11.0,
price=299.89,
prqt=1.0
},
{
eventConfig={
success=0.0,
bgColor=#C0392B,
successText=No
},
name=intermission,
prid=11.0,
price=299.89,
prqt=1.0
}
]
}
I'm trying to convert into json string but getting error while converting
i need output as
{
"filters": [
{
"eventConfig": {
"success": 1,
"bgColor": "#27AE60",
"successText": "Yes"
},
"prid": 9,
"name": "abc",
"prqt": 1,
"price": 199.89
},
{
"eventConfig": {
"success": 1,
"bgColor": "#27AE60",
"successText": "Yes"
},
"name": "abc",
"prid": 10,
"price": 99.89,
"prqt": 1
},
{
"eventConfig": {
"success": 0,
"bgColor": "#C0392B",
"successText": "No"
},
"name": "internet",
"prid": 11,
"price": 299.89,
"prqt": 1
},
{
"eventConfig": {
"success": 0,
"bgColor": "#C0392B",
"successText": "No"
},
"name": "intermission",
"prid": 11,
"price": 299.89,
"prqt": 1
}
]
}
Please use the following code snippet to Parse this response.
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray filtersArray = jsonObject.getJSONArray("filters");
for (int i = 0; i < filtersArray.length(); i++) {
//Parsing eventConfig object
JSONObject eventConfigObject = filtersArray.getJSONObject(i).getJSONObject("eventConfig");
int success = eventConfigObject.getInt("success");
String bgColor = eventConfigObject.getString("bgColor");
String successText = eventConfigObject.getString("successText");
//Parsing other objects
int prid = filtersArray.getJSONObject(i).getInt("prid");
String name = filtersArray.getJSONObject(i).getString("name");
int prqt = filtersArray.getJSONObject(i).getInt("prqt");
int price = filtersArray.getJSONObject(i).getInt("price");
}
} catch (Exception e) {
e.printStackTrace();
}
Happy Coding!! Thanks..!
{
"LIST": [
{
"GroupName": "گالری",
"GroupID": "1",
"GType": "gallery1",
"list": [
{
"Title": "food",
"RefType": "app",
"PicUrl": "http://tv.dmedia.ir/images/icon/slide2.jpg",
"RefID": "194"
},
{
"Title": "drink ",
"RefType": "app",
"PicUrl": "http://tv.dmedia.ir/images/icon/slide1.jpg",
"RefID": "199"
}
]
},
{
"GroupName": "ویدئوهای برگزیده",
"GroupID": "2",
"GType": "apk",
"list": [
{
"AppID": "333",
"Packname": "shadkami",
"AppName": "شادکامی و مثبت اندیشی",
"AppSize": 13066,
"VersionCode": "0",
"IconURL": "http://tv.dmedia.ir/paneluser/uploads/files/113.f402cee9889beb52e844012aec28ab0d.mp4/icon/becc1783d1263730b177317f4950f187.jpg",
"IconURL2": "",
"Specials": "0",
"DownloadsCount": "0",
"LikesCount": "0",
"GroupID": "16",
"AppPrice": 0,
"AppAutor": null,
"AppRate": 0,
"GroupType": "1"
},
{
"AppID": "332",
"Packname": "afzayeshetemad",
"AppName": "افزایش اعتماد به نفس",
"AppSize": 25132,
"VersionCode": "0",
"IconURL": "http://tv.dmedia.ir/paneluser/uploads/files/113.b52e30b721705d884832ffc7aa533375.mp4/icon/63c178ab34267b3e25691a7c1b6914c8.jpg",
"IconURL2": "",
"Specials": "0",
"DownloadsCount": "0",
"LikesCount": "0",
"GroupID": "16",
"AppPrice": 0,
"AppAutor": null,
"AppRate": 0,
"GroupType": "1"
}
]
}
]
}
try {
JSONObject object = new JSONObject(respond);
JSONArray jsonArrayLIST = object.getJSONArray("LIST");
ArrayList<ListViewMain> listmain = new ArrayList<>();
ListViewMainAdapter adapter = new ListViewMainAdapter(MainActivity.this, R.layout.list_view_main, listmain);
list_view_main.setAdapter(adapter);
for (int i = 0; i < jsonArrayLIST.length(); i++) {
JSONObject objectLIST = jsonArrayLIST.getJSONObject(i);
JSONArray jsonArraylist = objectLIST.getJSONArray("list");
Toast.makeText(MainActivity.this, jsonArraylist.toString(), Toast.LENGTH_SHORT).show();
for (int j = 0; j < jsonArraylist.length(); j++) {
JSONObject objectlist = jsonArraylist.getJSONObject(j);
String Packname= objectlist.getString("Packname");
Log.i("Log", "SHOW Packname " + Packname);
listmain.add(new ListViewMain(Packname));
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
In can't get String value in third Arraylist "list":[ because is same name with Second ArrayList "list":[.
But when I Toast Second ArrayList I see Second,third Arraylist but I can't get String third value and show nothing in Log or my listView or Toast String Value
how can I access Packname?
you have no Packname in your first array, please revise this
for (int j = 0; j < jsonArraylist.length(); j++) {
JSONObject objectlist = jsonArraylist.getJSONObject(j);
if(objectlist.has("Packname")){
String Packname= objectlist.getString("Packname");
Log.i("Log", "SHOW Packname " + Packname);
listmain.add(new ListViewMain(Packname));
}
}
adapter.notifyDataSetChanged();
please try this