How to display the suggestion for autocomplete field using json file? - java

I have this json that has " product code" inside this product code has another jsonobject and string.
What I want is that when I input the "product code" the suggested description will show.
I already get the display for suggested description when I input the product description code but it seems that it displaying in wrong way.
What I mean is that when I type the "product code" "BI" the display for suggested description is like this
{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}
here is my json
{
"BI": {
"desc": {
"MBIK": "MOUNTAIN BIKE",
"FBIK": "FOLDING BIKE",
"EBIK": "E-BIKE",
"OTHER": "OTHER"
},
"brand": {
"GNT": "GIANT",
"TRL": "TREEK",
"CNN": "CNDALE",
"STC": "SANTA",
"SCT": "SCOTT"
},
"category": "BICYCLE & EBIKE STORE"
},
"CA": {
"desc": {
"CARA": "CAR AUDIO",
"CARS": "CAR SPEAKER",
"TIRE": "CAR TIRE",
"OTHER": "OTHER"
},
"brand": {
"AIC": "AICHI",
"BRI": "BRIGDESTONE",
"CON": "CONTINENTAL",
"DUN": "DUNLOP",
"FAL": "FALKEN GR"
}
"category": "CAR ACCESORIES"
},
and so on.. {
}
}
here is the my code to parse my json to my fragment
private void loadLookupCategoryJson() {
mLookupProducts = new ArrayList<>();
mArrayStringLookupProduct = new ArrayList<>();
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);
String category = obj.getString(Keys.CATEGORY);
LookupProducts lookupProduct = new LookupProducts(key, brand, desc, category);
mLookupProducts.add(lookupProduct);
mArrayStringLookupProduct.add(String.valueOf(brand));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
and here is my to get the brand dynamic field
} else if (format.equalsIgnoreCase(Keys.AUTO_COMPLETE_FIELD)) {
addTextViews(title);
addAutoCompleteField(desc, inputType, title, mKeys.get(i), mArrayStringLookupProduct, maxLength, minLength);
}
I expect the output should be like this
INPUT TEXT: T
SUGGESTED DISPLAY:GIANT
TREEK
SANTA
SCOTT
Display all values with "T"
actual output
INPUT TEXT: BI
SUGGESTED DISPLAY:{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}

In this line of code - mArrayStringLookupProduct.add(String.valueOf(brand));
You are adding whole jsonObject into mArrayStringLookupProduct ArrayList.
You only want JSONObject brand's values in this ArrayList.
You can make the following changes-
JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
JSONObject desc = obj.getJSONObject(Keys.CATEGORY_DESC);
String category = obj.getString(Keys.CATEGORY);
lookupProduct = new LookupProducts(key, brand, desc, category);
mLookupProducts.add(lookupProduct);
// iterate every brand key, fetch its value and add in arrayList
Iterator<String> brandKeys = brand.keys();
while(brandKeys.hasNext()) {
String bKey = brandKeys.next();
mArrayStringLookupProduct.add((String) brand.get(bKey));
}

Related

How to convert all json file. Program read path of JSON file

I try convert json file to object, it run when i use one trans-unit but appears problem when i try read two trans unit. Program read only path of json. I use JSONParser and JSONObject
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(args[1]));
JSONObject transUnit = (JSONObject) obj.get("trans-unit");
id = (String) transUnit.get("id");
if (id == null) {
System.out.println("Id is required parameter!");
return;
}
source = (String) transUnit.get("source");
JSONObject targetList = (JSONObject) transUnit.get("target");
if (targetList != null) {
qualifier = (String) targetList.get("state-qualifier");
targetText = (String) targetList.get("target-text");
}
JSONObject altTransList = (JSONObject) transUnit.get("alt-trans");
if (altTransList != null) {
extype = (String) altTransList.get("extype");
match = (String) altTransList.get("match-quality");
origin = (String) altTransList.get("origin");
sourceAlt = (String) altTransList.get("source");
targetAlt = (String) altTransList.get("target");
}
It run, when I read json file below
"trans-unit": {
"id": "t1",
"source": "Text text text text",
"target": {
"state-qualifier": "exact-match",
"target-text": "Tekst tekst tekst tekst",
},
"alt-trans": {
"extype": "exact-match",
"match-quality": "100%",
"source": "Text text text text",
"target": "Tekst tekst tekst tekst"
}
}
}
But when a read this json:
{
"trans-unit": {
"id": "t1",
"source": "Text text",
"target": {
"state-qualifier": "match",
"target-text": "Tekst tekst"
},
"alt-trans": {
"extype": "match",
"match-quality": "100%",
"source": "Text text",
"target": "Tekst tekst"
}
},
"trans-unit": {
"id": "t2",
"source": "Hello there.",
"target": {
"state-qualifier": "mt",
"target-text": "Cześć"
},
"alt-trans": {
"extype": "TRANSLATION",
"match-quality": "nmt",
"source": "Hello there.",
"target": "Cześć"
}
}
}
JSON dont't read trans unit with id t1 but read only tran-unit t2.
I don't know where the problem lies. Can anyone help?
What do you really want to achieve?
I think the problem is, that the second json data is kind of List or Array.
So you only will get the last "object".
Are you allowed to use any library like gson ? This will make it a lot easier.

Json data parsing and display in List using Codename one

Here I have to parse JSON data getting from Facebook and display in list using Codename one so how can I cast ArrayList with Map.
Here is my Json data
{
"posts": {
"data": [
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-14T19:08:34+0000",
"id": "1323317604429735_1307213186040177"
},
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-02T14:22:50+0000",
"id": "1323317604429735_1295671703860992"
},
{
"message": "Hurray....... INDIA WON KABBADI WORLD CUP 2016",
"created_time": "2016-10-22T15:55:04+0000",
"id": "1323317604429735_1182204335207730"
},
{
"story": "Gaurav Takte updated his profile picture.",
"created_time": "2016-10-21T05:35:21+0000",
"id": "1323317604429735_1180682575359906"
},
{
"message": "Friends like all of you … I would love to keep forever.
#oldmemories with # besties
#happydays",
"story": "Gaurav Takte with Avi Bhalerao and 5 others.",
"created_time": "2016-10-21T05:33:55+0000",
"id": "1323317604429735_1180682248693272"
},
{
"message": "\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.
तुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना
सुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच
बाप्पाच्या चरणी प्रार्थना. \"
गणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!",
"story": "Gaurav Takte with Avi Bhalerao and 18 others.",
"created_time": "2016-09-05T05:06:58+0000",
"id": "1323317604429735_1133207030107461"
}
]
}
}
So how can I parse it and also display in list manner in Codename one.
Check out the JSONParser class in Codename One which the developer guide covers.
The sample from the guide is pasted below but I suggest reading it there as it is properly annotated there:
Form hi = new Form("JSON Parsing", new BoxLayout(BoxLayout.Y_AXIS));
JSONParser json = new JSONParser();
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), "/anapioficeandfire.json"), "UTF-8")) {
Map<String, Object> data = json.parseJSON(r);
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
String url = (String)obj.get("url");
String name = (String)obj.get("name");
java.util.List<String> titles = (java.util.List<String>)obj.get("titles");
if(name == null || name.length() == 0) {
java.util.List<String> aliases = (java.util.List<String>)obj.get("aliases");
if(aliases != null && aliases.size() > 0) {
name = aliases.get(0);
}
}
MultiButton mb = new MultiButton(name);
if(titles != null && titles.size() > 0) {
mb.setTextLine2(titles.get(0));
}
mb.addActionListener((e) -> Display.getInstance().execute(url));
hi.add(mb);
}
} catch(IOException err) {
Log.e(err);
}
hi.show();
Try this,
JSONObject obj=new JSONObject(response);
JSONObject posts_obj=obj.getJSONObject("posts");
JSONArray data_arr=posts_obj.getJSONArray("data");
for(int i=0;i<data_arr.length();i++) {
JSONObject data_obj=data_arr.getJSONObject(i);
String story = data_obj.getString("story");
String created_time = data_obj.getString("created_time");
String id = data_obj.getString("id");
if(data_obj.has("message")) {
String message = data_obj.getString("message");
}
}

org.json.JSONException: No value for Name JSON extraction error

I am getting this error when I try to get the value for "Name" out of the following JSON:
{
"edges": [
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
},
{
"node": {
"Name": "Sugarloaf Mountain",
"Latitude": 45.0314,
"Longitude": 70.3131
}
}
]
}
This is the snippet of code I am using to try and access these values, but I am just testing getting "Name" for now:
String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + "\"" + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
JSONObject node = jsonArray.getJSONObject(i);
Log.d(TAG, node.toString(1));
String name = node.getString("Name");
Log.d(TAG, name);
}
My output looks like this:
{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
}
org.json.JSONException: No value for Name
I understand that I could use optString and not get the error, but that will not give me the data stored in each node.
Here is a version that works with your unaltered JSON:
public static void main(String... args)
{
String json = "{\"data\":{\"viewer\":{\"allMountains\":{\"edges\":[{\"node\":{\"Name\":\"Sunday River\",\"Latitude\":44.4672,\"Longitude\":70.8472}},{\"node\":{\"Name\":\"Sugarloaf Mountain\",\"Latitude\":45.0314,\"Longitude\":70.3131}}]}}}}";
JSONObject obj = new JSONObject(json);
JSONObject data = obj.getJSONObject("data");
JSONObject viewer = data.getJSONObject("viewer");
JSONObject allMountains = viewer.getJSONObject("allMountains");
// 'edges' is an array
JSONArray edges = allMountains.getJSONArray("edges");
for (Object edge : edges) {
// each of the elements of the 'edge' array are objects
// with one property named 'node', so we need to extract that
JSONObject node = ((JSONObject) edge).getJSONObject("node");
// then we can access the 'node' object's 'Name' property
System.out.println(node.getString("Name"));
}
}

How to override the 2nd Object JSON with 1st JSON object

I have a situation where I need to override 2nd JSON object value to 1st.
JSON original :-
{
"products": {
"productsApp15": {
"status": "active",
"attribute_set": "Apparel",
"name": "productsApp16",
"product_type": "product",
"code": "productsApp16"
}
}
}
My 1st object :-
{
"productsApp15": {
"attribute_set": "Apparel",
"status": "active",
"name": "productsApp16",
"product_type": "product",
"code": "productsApp16"
}
}
My 2nd object :-
{
"attribute_set": "Apparel",
"status": "active",
"name": "productsApp16",
"product_type": "product",
"code": "try"
}
If you see the value of key -> code is updated here. I want this change in my real or 1st JSON object so I can pass it to my Payload
My Code:-
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONObject jsonObject1 = (JSONObject) jsonObject.get("products");
JSONObject jsonObject2 = (JSONObject)jsonObject1.get("productsApp15");
String firstName = (String) jsonObject2.get("code").toString();
System.out.println("The first name is: " + firstName);
jsonObject2.remove("code");
jsonObject2.put("code", "try");
JSONObject jsonObject3 = (JSONObject)jsonObject1.get("productsApp15");
String firstName2 = (String) jsonObject2.get("code").toString();
System.out.println("The first name is: " + jsonObject3);
JSONObject combined = new JSONObject();
combined.put("Object1", jsonObject1);
combined.put("Object2", jsonObject3);
String firstName3 = (String) jsonObject2.get("code").toString();
System.out.println("The first name is: " + combined);
My Main objective :- I am reading a file which contain my JSON, As you can see my object is again inside an another object .
I want to update the value and then want to pass it to payload.
But how to get the original JSON structure with updated value?
Is it possible?
By Constructing the Java classes against the structure that is required in JSON, this can be achieved.
Messing up with JSON with JSON readers and parser is risky.
public class Products{
private List<Product> productsList;
}
public class Product{
private Map<String, ProProps> map = new HashMap<>();
class ProProps{
private String code;
private String name;
...
}
}
This gives you to map the objects and values.
Get the value of product that you want by key and replace the required props that you want.
Though the conversion of Java - Json takes place, there can be many extensions that can happen when you develop.
You can use this example to convert and do the manipulations required.

Android: Dynamically Get JSON Array Key Name From JSON

I have a json link, if we open it I get a following result
{
"Status": "Success",
"All_Details": [{
"Types": "0",
"TotalPoints": "0",
"ExpiringToday": 0
}],
"First": [{
"id": "0",
"ImagePath": "http://first.example.png"
}],
"Second": [{
"id": "2",
"ImagePath": "http://second.example.png"
}],
"Third": [{
"id": "3",
"ImagePath": "http://third.example.png"
}],
}
What I need is, I want to dynamically get all the key names like status, All_details, First etc.
And I also want to get the data inside the All_details and First Array.
I used following method
#Override
public void onResponse(JSONObject response) throws JSONException {
VolleyLog.d(TAG, "Home Central OnResponse: " + response);
String statusStr = response.getString("Status");
Log.d(TAG, "Status: " + statusStr);
if (statusStr.equalsIgnoreCase("Success")) {
Iterator iterator = response.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
}
}
}
I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???
First, to get the keynames, you can easily iterate through the JSONObject itself as mentioned here:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Then, to get the values of the array:
JSONArray arr = response.getJSONArray(key);
JSONObject element;
for(int i = 0; i < arr.length(); i++){
element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details)
}
If you want to get the JSON array from the response JSONObject you can use the JSONArray class. JSONObject has a method to get a JSONArray: getJSONArray(String). Remember to catch the JSONException when trying this. This exception will be thrown if there is no key for example.
Your code could look like this (only the while loop):
while (iterator.hasNext()) {
String key = (String)iterator.next();
try {
JSONArray array = response.getJSONArray(key);
// do some stuff with the array content
} catch(JSONException e) {
// handle the exception.
}
}
You can get the values from the array with the methods of JSONArray (see the documentation)
Something like this will allow you to iterate on array and individual fields once you have extracted the keys using what you have done. Instead of "Types" use the key variable you will create before this.
JSONArray allDetails = response.getJsonArray("All_Details")
for (int i = 0 ; i < allDetails.length(); i++) {
JSONObject allDetail = allDetails.getJSONObject(i);
allDetails.getString("Types");
}
First of all I want to inform you that it's not a valid JSON. Remove the last Comma (,) to make it valid.
Then you can Iterate like here
JSONArray myKeys = response.names();
Try this one
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
try {
String dynamicKey = (String) keys.next();//Your dynamic key
JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories