Amit Sharma Amit Sharma - 13 days ago 6
JSON Question

jsonObject.getString("String in UTF8" ) giving blank

I am fetching a string from my MySql DB on and online server using webservice in JSON format.
I am able to see that Android Studio is fetching it correctly as I see it in debugging mode.
But when I go ahead and add it to a List list, I get nothing.

Here's some more info:
What I am getting:

{"products":[{"veg_name_eng":"Corn","veg_name_hindi":"मक्का"}],"success":1}


My concern is with: "veg_name_hindi":"मक्का"

When I go ahead and try to put it in a dataitem list, I get nothing:

public static List<DataItem> dataItemList;
dataItemList.add(jsonObject.getString(veg_name_eng),jsonObject.getString(veg_name_hindi))


veg_name_eng and veg_name_hindi are the column names at my table.

After the above code I get dataItemList = null, So nothing is adding to it.

In my server side MySql DB, I am using UTF-8 encoding.

I am using android studio.

UPDATE 1:

I am parsing the JSON as :

JSONObject jsonObject = new JSONObject(myJSONString);
veg_list = jsonObject.getJSONArray("products");
try {
while (TRACK < veg_list.length()) {
JSONObject jsonObject = veg_list.getJSONObject(TRACK);
addItem(new DataItem(jsonObject.getString(veg_name_eng), jsonObject.getString(veg_name_hindi)));
TRACK = TRACK + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}


// and the addItem function is as follows:

private static void addItem(DataItem item) {
dataItemList.add(item); //While Debugging, I can see that value of item is correct. (i.e., item: DataItem{veg_name_eng='Cork', veg_name_hindi='मक्का'} )
dataItemMap.put(item.getVeg_id(), item);
}

Answer

Firstly, Make a model of the your JSON String using

http://json2java.azurewebsites.net/

and then map your JSON String to your Model using Gson. It's much easy to use.

Another way to get your required String for this particular result is parse json string yourself.

For Example :

String vegNameEng,vegNameHindi;

vegNameEng = vegNameHindi = "";

try{
    JSONObject obj = new JSONObject(yourJsonString);
    JSONArray arr = obj.getJSONArray("products");
    vegNameEng = arr.getJSONObject(0).getString("veg_name_eng");
    vegNameHindi = arr.getJSONObject(0).getString("veg_name_hindi");
}catch(JSONException ex){

}

Now vegNameEng and vegNameHindi have the required data.