I'm trying to Parse the below JSONString
[[{"0":"
","title":" Technical Support Analyst in Noida","1":"
","Company Name":" Oracle","2":"
","Category":"Fresher","3":"
","Job Type":"Full Time","4":"
","Location":"Noida","5":"
","Job Qualification":"BE\/BTch\/Bsc\/Others","6":"
","Job Experience":"Freshers","7":"
","Job postdate":"2013-6-05","8":"
"}]]
Here My Code:
// try parse the string to a JSON object
try {
//jObj = new JSONObject(JsonString);
JSONArray ja = new JSONArray(result);
int size = ja.length();
Log.d("tag", "No of Elements " + ja.length());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Could any one help,My Code is not Working?
I want to Parse title,CompanyName,Category Etc...
You need to create JSONArray from your jsonstring.
You have JSONArray inside JSONArray and then JSONObect..
try {
JSONArray ja = new JSONArray(buffer.toString());
JSONArray innerJsonArray = ja.getJsonArray(0);
JSONObject object = innerJsonArray.getJSONObject(0);
String title = object.getString("title");
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Take a look at this Json parsing guide using native tools and Gson library that I wrote:
Json Parsing
Maybe you will find it useful.
You can download the full project from there as well to run and test it for yourself.
You need to structure your json.
There is no array named "result". What you have to do is to name every element of the json with a unique name, so as to fetch it.
such as
{"result":
["result1":["result2":{"0":"
","title":" Technical Support Analyst in Noida","1":"
","Company Name":" Oracle","2":"
","Category":"Fresher","3":"
","Job Type":"Full Time","4":"
","Location":"Noida","5":"
","Job Qualification":"BE\/BTch\/Bsc\/Others","6":"
","Job Experience":"Freshers","7":"
","Job postdate":"2013-6-05","8":"
"}]]}
You can try below code for parsing JSON
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea, Republic of"},
{"countryCode":"us","countryName":"United States"},
{"countryCode":"jp","countryName":"Japan"},
{"countryCode":"cn","countryName":"China"},
{"countryCode":"in","countryName":"India"}
]
}
parsing code
public static ArrayList<Country> ParseJson(String jsonstring) {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String status;
String message = "";
try {
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}
} catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
return arrCountries;
}
Related
i've got a problem to retrieve information by a JSON
The Raw Json is this
{"date":"{\"yesterday\":\"Wed 28\",\"today\":\"Thu
29\",\"tomorrow\":\"Fri 30\"}"
Now how i could take this Json and format in this?
{
"date":{
"yesterday":"Wed 28",
"today":"Thu 29",
"tomorrow":"Fri 30"
}
}
And then retry the date from the key?
String jsonStr = sh.makeServiceCall(url);
Log.e("RAW-JSON: ","Retrieve RAW-Json is "+jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray DATESTRING = jsonObj.getJSONArray("date");
JSONObject d = DATESTRING.getJSONObject(0);
String Ieri = d.getString("yesterday");
Log.e("DATE-JSON", "Retrieve DATE-Json is " + yesterday);
} catch (JSONException e) {
Log.e("ERROR", "Not a good result.");
e.printStackTrace();
}
}
I would strongly recommend use the library Gson to parse a JSON document, is much easier and elegant.
public static date parseJSON(String jsonArray) {
date yourDate = new date();
try {
yourDate = (gson.fromJson(jsonArray, date.class));
} catch (Exception e) {
e.printStackTrace();
}
return yourDate;
}
Then the class date is just a class with the same elements that exists in the JSON you want to read in your case:
public class date {
private String yesterday;
private String today;
private String tomorrow;
}
JSONArray DATESTRING = jsonObj.getJSONArray("date") is wrong because "date" is not an JsonArray but an JsonObject!
What you probably need to do is (assuming you want today's date):
String todaysDate = jsonObj.getJSONObject("date").getString("today");
Just simply replace \" with " to get clean json string and then parse the json to read data usig JSONObjct.
jsonStr = jsonStr.replace("\\\"", "\"");
JSONObject jsonObj = new JSONObject(jsonStr);
I'm currently trying to parse some JSON in my android application but I keep getting an error saying "No value for users"
This is the current code I am using:
JSONObject parentObject = new JSONObject(finalJSON);
JSONObject childObject = new JSONObject(String.valueOf(parentObject));
JSONArray parentArray = childObject.getJSONArray("users");
JSONObject finalObject = parentArray.getJSONObject(0);
String userName = finalObject.getString("username");
String profileLink = finalObject.getString("profileimage");
Log.d("JSON", String.valueOf(finalObject));
return profileimage+ " - " + profileLink ;
and here is my JSON:
{
"reply": {
"users": [
{
"userid": "001",
"loggedIn": 1,
"username": "joe.bloggs",
"profileimage": "http://127.0.0.1/joebloggs.png",
"realname": "Joe Bloggs",
}
]
}
}
Thanks in advance!
You forgot the reply level.
Here is what you should do.
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray userArray = parentObject
.getJSONObject("reply")
.getJSONArray("users");
JSONObject finalObject = userArray.getJSONObject(0);
you can't take new object for object inside object.
you have to do this for parse object inside object.
JSONObject object1 = new JSONObject(finalJSON);
JSONObject object2 = object1.getJSONObject("reply");
JSONArray jsonArray = object2.getJSONArray("users");
JSONObject object3 = jsonArray.getJSONObject(0);
try the following:
JSONObject root = null;
try {
root = new JSONObject("reply");
JSONArray childArray = root.getJSONArray("users");
String userName = childArray.getString(0);
.
.
.
} catch (JSONException e) {
e.printStackTrace();
}
I have an array of JSON strings like:
[{
"id":"BirthDate",
"field":"BirthDate",
"type":"date",
"input":"text",
"operator":"equal",
"value":"2016/04/07"
}]
I want to be able to iterate this array and want to get its id, field, value in Java
Using the below code I got an exception
"json object must begin with {"
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
JSONObject obj = new JSONObject(rules);
System.out.println("====obj===="+obj);
// boolean error = obj.getBoolean("error");
String id = obj.getString("id");
System.out.println("===id is===: "+id);
} catch (JSONException e){
e.printStackTrace();
}
You should instead create a JSONArray from the String and then iterate over the array. Modify your code as
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
// create the json array from String rules
JSONArray jsonRules = new JSONArray(rules);
// iterate over the rules
for (int i=0; i<jsonRules.length();i++){
JSONObject obj = jsonRules.get(i);
System.out.println("====obj===="+obj);
String id = obj.getString("id");
System.out.println("===id is===: "+id);
}
} catch (JSONException e){
e.printStackTrace();
}
Try this parsing your rulesinto a JSONArray:
String rules = "[{\"id\":\"BirthDate\",\"field\":\"BirthDate\",\"type\":\"date\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"2016/04/07\"}]";
try {
JSONArray obj = new JSONArray(rules); // parse the array
for(int i = 0; i < obj.length(); i++){ // iterate over the array
JSONObject o = obj.getJSONObject(i);
String id = o.getString("id");
System.out.println("===id is===: " + id);
}
} catch (JSONException e){
e.printStackTrace();
}
In the JSON you gave as example you just have one element in your array.
I am trying to make a search page for my andriod app using PHP,JSON and SQL.
here is the code that is giving me the error :
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
tempID += json_data.getString("ID") + "\n";
tempID += json_data.getString("heading") + "\n";
tempID += json_data.getString("rank") + "\n:";
}
arr = tempID.split(":");
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
}catch (Exception e){
String errMsg = "error when putting the json data in the list";
Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
}
i have already used this code on another page and it works perfectly but when using it another page/activity it gives me an error when trying to put the json data in listview.
i would guess the problem is when i am setting the ArrayAdapter, have i done anything wrong?
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
To answer your final question:
//array list
List<String> your_array_list = new ArrayList<String>();
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
your_array_list.add(json_data.getString("ID") + "\n");
your_array_list.add(json_data.getString("heading") + "\n");
your_array_list.add(json_data.getString("rank") + "\n:");
}
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,your_array_list));
//then, to get the items from inside the adapter:
for(String item_in_list : your_array_list){
System.out.println(item_in_list);
}
To answer the original question:
Check out http://jsonformatter.curiousconcept.com/ for formatting issues
Try looking at this info:
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
FYI: The inbuilt JSONObject and JSONArray cannot be used to get certain json responses.
You could try downloading a small library named "json-simple-1.1.1.jar" from this link https://json-simple.googlecode.com/files/json-simple-1.1.1.jar.
This is my json array creating with php.
I want to know bellow json array have correct syntax.
How to get the values withing android,because my sample code get some errors.
THIS IS PHP SCRIPT FOR JSON ARRAY GENARATING
public static function getCategory($_lgtime) {
$con = JsonDataManip::connect();
$stmt = $con->prepare("select * from " . _TABLE_CATEGORY . " where lgtime > ?");
$stmt->execute(array($_lgtime));
while ($row = $stmt->fetch()) {
$jsonArray['key'] = $row['key'];
$jsonArray['name'] = $row['name'];
$jsonArray['lgtime'] = $row['lgtime'];
$json[] = $jsonArray;
}
return $json;
}
usage php :
echo json_encode(JsonDataManip::getCategory('20140129184514895'));
GENARATED JSON ARRAY
[{
"key":"1",
"name":"Category 10",
"lgtime":"20140129184514896"
},
{
"key":"2",
"name":"Category 9",
"lgtime":"20140129184514896"
},
{
"key":"3",
"name":"Category 8",
"lgtime":"20140129184514896"
}]
ANDROID JSON PARSER FUNCTION
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsnArry = new JSONObject(jsonStr);
JSONArray jsonArray = jsnArry.getJSONArray("");
for(int i=0;i<jsnArry.length();i++){
Log.d("JSON PARSE",jsonArray.getJSONObject(i).getString("name"));
//contactList[i] =
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
ERROR
01-30 08:45:53.527: W/System.err(1507): org.json.JSONException: Value {"lgtime":"20140129184514896","key":"1","name":"Category 10"} at 0 of type org.json.JSONObject cannot be converted to JSONArray
Your PHP script returns a JSON array, not a JSON object. You should update your Android code like so:
if (jsonStr != null) {
try {
JSONArray json = new JSONArray(jsonStr);
for (int i=0; i < json.length(); i++) {
Log.d("JSON PARSE", json.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
Log.w("JSON PARSE", "Failed to parse JSON!", e);
}
}
To check if your JSON string is valid, please use this link JSONLint.
As far your error is concerned for your code, it clearly states that
type org.json.JSONObject cannot be converted to JSONArray
Possible Solution (if you are using Gson)
Your response from ServiceHandler would be a string. So convert that into a JSONObject and the pass that to JSONArray.
Example
JSONObject jsonObject = new JSONObject(<responseString>);
JSONArray jsonArray = jsonObject.getJSONArray();
Else
JSONObject jsonObject = new JSONObject(<responseString>);
String key = jsonObject.getJSONObject("key");
String name = jsonObject.getJSONObject("name");
String lgtime = jsonObject.getJSONObject("lgtime");
Then you can continue with your logic in the program.
{ "employees":[
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
]
}
Your opening and closing braces are missing. that is not a valid json array, The above is a sample array format