Parse JSON String array for individual strings/ints - android

I am getting information from a MySql DB via PHP. The information is returned in the following JSON array:
06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}}
The json is parsed and string is built using StringBuilder. Now that I have the information returned I want to parse it for the individual strings/ints it contains to put them in a local sqlite db.
Here are the two lines in question
userFunctions.getServerGameState(email, monster, qty, exp); //this line gets the JSON array and the above information is returned
db.saveLocalGameSate(monster, qty, exp); //this line should take that information take String monster int exp and int qty and put them in the local db.
How should I convert that returned information into an individual string and ints so that they can be used in the next line of code? Any direction to some resources would be very helpful.
update
I have added the following lines inbetween the two above lines of code, output is a null pointer exception
try {
JSONArray arr = new JSONArray(GameState);
JSONObject jObj = arr.getJSONObject(0);
String virtumon = jObj.getString("monster");
Integer qty = jObj.getInt("qty");
Integer exp = jObj.getInt("exp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

That's not actually a JSON array; it's a JSON object (cause of the curly braces instead of square brackets.)
One of the constructors to JSONObject() accepts a string containing JSON and will parse it and create a JSON object. I can't post links yet but see the JSONObject docs at d.android.com.
Once you have a JSONObject you can use getString(), getInt(), optString() and optInt() to pull out the data you need.
Assuming 'responseString' is the full response string:
try {
JSONObject responseObj = new JSONObject(responseString);
JSONObject gameStateObj = responseObj.getJSONObject("GameState");
String monsterType = gameStateObj.getString("monster");
int qty = Integer.parseInt(gameStateObj.getString("qty"));
int exp = Integer.parseInt(gameStateObj.getString("exp");
} catch (JSONException ex) {
e.printStackTrace();
}
"qty" and "exp" are strings in your json so you need to getString then convert to int. I think this code is correct; haven't tested it.

Related

Android, Iterate over JSON-fied dictionary

I have the following string, which was created using javascript JSON. (It's passed from a Webview to the native code using JavascriptInterface.)
{"var1":1,"var2":8}
How do I convert that into an object and then iterate over the key/value pairs? The names of the keys are NOT known in advance.
I have seen this JSON Array iteration in Android/Java and this Converting json string to java object? and this how to convert JSON string to object in JAVA android.
None of those seem to fit with my example, which is a dictionary with unknown key names. At least, it's certainly not clear to me which of the 15+ answers is relevant for my case.
The org.json library comes "for free" with Android, so I'd go with that. Usage when you don't know the keys ahead of time could be something like this:
try {
JSONObject jsonObject = new JSONObject(/* your json String here */);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
// do whatever you want with key/value
}
}
catch (JSONException e) {
// thrown when:
// - the json string is malformed (can't be parsed)
// - there's no value for a requested key
// - the value for the requested key can't be coerced to String
}
You can use it by converting the getting the json length like this:-
JSONObject obj = new JSONObject(response);
for (int i = 0; i < obj.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = obj.getJSONObject(i);
String aka=heroObject.getString("your key here");
}

How to use single word as JSON data in android?

I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.
My Code is -
JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.
URL just gives a word like - done that's it not even " or : { nothing
Then simply use the String variable s , don't convert it into json
plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception
try{
// exception will be thrown in case of invalid json
JSONObject jsonObject = new JSONObject(s);
}
catch(JSONException e){
// s containing a single word so use it as it is
}

Android - JSON get single value

I have a single JSON object like this
"stringData"
with no column names or anything just a single string
I'm confused how to get that value with no column names
edit the following code to get that single value ?
private void showJSON(String response){
String value="";
try {
JSONObject jsonObject = new JSONObject(response);
value = jsonObject. ??????
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Value:\t"+value);
}
your response is a string but not in json form. so convert this string into jsonObject give JSONException. So. you can do two things 1. first use this string without making jsonobject OR 2. send string in json form from server than convert the string into jsonobject and use.

how to get data from nested json which is not having name in android?

i have a JSON like below.
this is sample json.. i have my json structure like this. if this json has any error please ignore that.
[
[
"{"category_id":1,"category_name":"1Appetizers","image_id":0}",
"{"category_id":13,"category_name":"Buffet","image_id":0}"
],
[
"{"subcategory_id":1,"category_id":12,"subcategory_name":"Beer","image_id":0}",
"{"subcategory_id":2,"category_id":12,"subcategory_name":"Wine","image_id":0}"
],
[
"{"menucategory_id":1,"menucategory_id":12,"menucategory_name":"dosa","image_id":0}",
"{"menucategory_id":2,"menucategory_id":12,"menucategory_name":"idly","image_id":0}"
]
]
how do i parse this JSON in android. i want to show category_name in one page and other details in some other page. there is no name for object.
Like the other commenters have mentioned this is not real JSON.
But here is an attempt to answer your question anyway.
I would create objects that represents the data you want to serialize and deserialize to and form JSON. It looks like you would have objects Category, Subcategory, and MenuCategory. Then you would probably have another object that holds lists of those three objects.
Then I would use GSON to serialize and deserialize your object. Let it do the heavy lifting for you.
try the following code. it might help you
// say you have your json in a String named jsonString
try
{
JSONArray array = new JSONArray(jsonString);
JSONArray firstJsonArray = array.getJSONArray(0);
JSONArray secondJsonArray = array.getJSONArray(1);
JSONArray thirdJsonArray = array.getJSONArray(2);
for (int i = 0; i < 2; i++)
{
JSONObject firstJsonObject = firstJsonArray.getJSONObject(i);
JSONObject secondJsonObject = secondJsonArray.getJSONObject(i);
JSONObject thirdJsonObject = thirdJsonArray.getJSONObject(i);
String categoryName = firstJsonObject.getString("category_name");
String subcategoryName = secondJsonObject.getString("subcategory_name");
String menucategoryName = thirdJsonObject.getString("menucategory_name");
// Now here you can use these values to do anything
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

parsing JSON using GSON that has arrays

I've used GSON to retrieve a simple piece of JSON that didn't include arrays, and I placed them into a list of objects:
Type listType = new TypeToken<List<SingleEvent>>(){}.getType();
List<SingleEvent> events = new Gson().fromJson(jsonResponse, listType);
SingleEvent is the class I created and just included simple string variables.
Now, I want to create an object that can take Arrays from JSON strings.
[{"ticketmaster":"http:\/\/www.ticketmaster.ca","images":["http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/SNW_4.jpg","http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/AB.jpg","http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/L5Y.jpg","http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/TOS.jpg"]}]
So, in my object that will hold this data I just made a variable like this:
private ArrayList images;
I get a warning, but I'm sure how to handle incoming json arrays.
But what if you can parse the same JSON response using native classes?
Here is a simple try:
try {
JSONObject obj = new JSONObject("Your JSON String");
JSONArray array = obj.getJSONArray("images");
for(int i=0; i<array.length(); i++)
{
System.out.println("=====> Image at index "+i+"==>"+array.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources