how to iterate json String - java

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.

Related

How to get key from json object

I have the json array :
{"objets":{"1":"Question","2":"Response"},"success":true}
I want to test if the text selected on spinner exist in the array it will return the number (1 or 2).
Here is what I've done until now :
String responseContent = response.asString();
Log.d("OBJECTS", responseContent);
try {
JSONObject jobj = new JSONObject(responseContent);
JSONObject users = jobj.getJSONObject("objetcs");
Log.e("hello", String.valueOf(users));
if(users.toString().contains(spinner_objet.getSelectedItem().toString().trim())){
Log.e("hello", "it exist");
String user=users.getString("id");
Log.e("hello1", String.valueOf(user));
}
} catch (JSONException e1) {
e1.printStackTrace();
}
But I'm not getting any thing, can any one help me with this ?
You can parse your Json into a hashMap like so :
JSONObject object = new JSONObject();
Map<String,Integer> map = new HashMap<>();
while (object.keys().hasNext() ){
Integer key = (Integer) object.keys().next();
map.put((String) object.get(String.valueOf(key)), key);
}
You can then use the values of the map to put in the spinner.
map.values();
Whenever the user selects from the spinner, you can get the id from the map.

Array inside an array using JSON

This is code in JAVA I used JSONArray and method JSONarray.put(string);
public JSONArray getChart() {
Connection con = getConnectionObject();
Statement st = null;
ResultSet rs = null;
JSONObject jCharto = new JSONObject();
JSONArray arr = new JSONArray();
try {
st = con.createStatement();
String query = "select count(books_issued) as books_issued,command from fact_aaglib, school where fact_aaglib.school_name = school.school_name group by command;";
rs = st.executeQuery(query);
System.out.println("['Command','Book Issued'],");
while (rs.next())
{
String zone = rs.getString("command");
arr.put(zone);
int booksissued = rs.getInt("books_issued");
arr.put(booksissued);
}
System.out.println(arr+",");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return arr;
}
Here is my output
['Command','Book Issued'],["Central",324,"Southern",312,"South-West",192,"Eastern",264,"Northern",84,"Western",396],
But actual I want output like this:
[
['Command', 'Books Issued'],
["Central",324],["Southern",312],
["South-West",192],
["Eastern",264],
["Northern",84],
["Western",396]
]
And this data is using in google charts to draw bar chart .
A JSONArray is not limited to strings.
You need to create one array for holding records, then create a new one for each pair or records. Here is the basic idea:
// create the "top" array
JSONArray topArray = new JSONArray();
// add your static "headers"
JSONArray headers = new JSONArray();
headers.put("Command");
headers.put("Book Issued");
topArray.put(headers);
while (rs.next()){
// create a new array for the current record
JSONArray recordArray = new JSONArray();
// populate the record array
String zone = rs.getString("command");
recordArray.put(zone);
int booksissued = rs.getInt("books_issued");
recordArray.put(booksissued);
// append the record array to the top array
topArray.put(recordArray);
}
return topArray;

Modifying/Updating values inside a jsonArray?

What I want to do is at a particular index position change/replace a value inside a json array.After going through the documentation at http://www.json.org/javadoc/org/json/JSONArray.html I found out that jsonArray does not have a getIndex() method.In this situation how do I update my json array at a given index position.
This is the method that creates a json array in my android code.
private void createJsonArray() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
String invNumber = textViewInvNo.getText().toString();
String bcode = barCode.getText().toString();
String description = itemDesc.getText().toString();
String wt = weightLine.getText().toString();
String rateAmt = rateAmount.getText().toString();
String making = makingAmount.getText().toString();
String netr = netRate.getText().toString();
String iTotal = itemtotal.getText().toString();
String vatAmt = textViewVat.getText().toString();
String sumAmt = textViewSum.getText().toString();
String crtDate = textViewCurrentDate.getText().toString();
try {
jsonObject.put("custInfo", custSelected.toString());
jsonObject.put("invoiceNo", invNumber);
jsonObject.put("barcode", bcode);
jsonObject.put("description", description);
jsonObject.put("weight", wt);
jsonObject.put("rate", rateAmt);
jsonObject.put("makingAmt", making);
jsonObject.put("net_rate", netr);
jsonObject.put("itemTotal", iTotal);
jsonObject.put("vat", vatAmt);
jsonObject.put("sum_total", sumAmt);
jsonObject.put("bill_type", billType);
jsonObject.put("date", crtDate);
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemSelectedJson.put(index, jsonObject);
index++;
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is the code that I use to update my json array which contains a json object.
try {
itemSelectedJson.getJSONObject(i).put("net_rate",netChange);
Log.d("NETRATE_TW",itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Now the problem with this code is it updates the jsonArray everytime a new item is added to the code.So the first object values are the same as the last object.
Also note that I am using this code inside a text watcher.So the afterTextchanged() method looks like this.
#Override
public void afterTextChanged(Editable s) {
String netChange = netRate.getText().toString();
final int row_id = (int) newRow.getTag();
if ((row_id<0) || (row_id> itemSelectedJson.length())){
return;
}
try {
itemSelectedJson.getJSONObject(row_id-1).put("net_rate",netChange);
Log.d("NETRATE_TW",itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
};
This is the snapshot of what my database looks like.
A jSONObject(which is a collection of name,value pairs) can be converted into a JSONArray which is an ordered array of the "values" in the JSONObject.
This can be done using the .toJSONArray() method.
When you need to replace/update the JSONArray, you may use the method
.put(int index, java.util.Map value)
Unlike how you are doing at present, i.e getting the object and setting a new key and value.
http://www.json.org/javadoc/org/json/JSONArray.html#put(int, java.util.Map)
As I understood, your problem is in creating multiple JSONObjects in your JSONArray with the same values, and that's because you can't get the index of a created JSONObject inside your JSONArray, and to overcome this problem, you can easily create a compound JSONObject that contains your JSONObjects instead of a JSONArray contains JSONObjects, and the object name will be anything unique in your JSONObject data, and when you make any changes or add any item it will either be added as a new object if it doesn't exist or it will overwrite the existing object if it added before, for example let's suppose that barcode value is unique in your data, so the code will be like the following:
// declaring itemSelectedJson as JSONObject
JSONObject itemSelectedJson = new JSONObject();
.
.
.
// when wanting to add a new item
itemSelectedJson.put(jsonObject.getString("barcode"), jsonObject);
and to retrieve the data you simple iterate through this JSONObject:
Iterator<?> keys = itemSelectedJson.keys();
JSONObject single_item;
while(keys.hasNext()) {
String key = (String)keys.next();
single_item = itemSelectedJson.getJSONObject(key);
// do what do you want here
}

Android data transferring with Json issue

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

How to Parse the JSON String Android

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;
}

Categories