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
Related
I am trying to update a JSON file with input from an HTTP GET request. I so far have the following below but it is returning an org.json.simple.JSONObject cannot be cast to org.json.JSONObject. I have tried numerous methods with this but I am hitting the same hurdle and going round in circles. Please help me.
The goal after seeing the revised JSON data outputted to system is to write it back to file.
HTTP GET RESPONSE FORMAT:
{
array: [
"data1" : "data 1",
"data2" : "data 2",
"data3" : "data 3",
"data4" : "data 4",
"data5" : "data 5",
]
}
EXISTING JSON FILE (please note no array):
{
"data5" : "data 5",
"dataA" : "data A",
"dataB" : "data B",
"dataC" : "data C",
"dataD" : "data D",
}
HTTP GET CODE:
#Component
public class ServiceConnector {
private final HttpClient client;
public ServiceConnector() {
client = HttpClientBuilder.create().build();
}
public String get(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
HttpGet request = new HttpGet(url);
request.addHeader("Accept", acceptHeader);
if (bearerToken.isPresent()) {
request.addHeader("Authorization", "Bearer " + bearerToken.get());
}
try {
HttpResponse response = client.execute(request);
//new code
String data = EntityUtils.toString(response.getEntity());
JSONObject root = new JSONObject(data);
JSONArray results = root.getJSONArray("results");
for(int i = 0; i < results.length(); i++) {
JSONObject jsonResult = results.getJSONObject(i);
OBLI Result = new OBLI();
String data1 = jsonResult.getString("data1");
String data2 = jsonResult.getString("data2");
String data3 = jsonResult.getString("data3");
String data4 = jsonResult.getString("data4");
String data5 = jsonResult.getString("data5");
try {
FileReader reader = new FileReader("/root/Desktop/data.json");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(reader);
System.out.println(jsonObject);
JSONObject dataObj = (JSONObject) jsonObject.get("data5");
System.out.println(periodObj);
dataObj.put("data5",data5);
System.out.println(jsonObject);
}
catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
e.printStackTrace();
}
}
//end of new code
if (response.getStatusLine().getStatusCode() == 401) {
throw new UnauthorizedException();
}
return "something else later";
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I think the problem with "HTTP GET RESPONSE FORMAT".
maybe right JsonArray format is:-
{
"array": [{
"data1" : "data 1",
"data2" : "data 2",
"data3" : "data 3",
"data4" : "data 4",
"data5" : "data 5"
}]
and then you can change
JSONArray results = root.getJSONArray("results"); to JSONArray results = root.getJSONArray("array");
and then use for-each loop for get one by one Object With help of DTOs.
}
So, you can convert jsonArray to JsonObject.
The answer to this question was that org.json and org.json.simple did not create JSONObjects that were interchangeable.
I used Jackson library and ObjectMapper, JsonNode, and ObjectNode to update the file - ultimately removing the org.json.simple library altogether.
I have a sample JSON as below. I need to get the individual fields like ASIdentifer and ExternalIdentifer. I have stored this JSON data in a string.
Using GoogleJson as the module(ggson)
JSON data:
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
I created the POJO classes and parsed the data using below code
data = new Gson().fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), Data.class);
System.out.println(data);
Output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}
String jsonInString = gson.toJson(data);
System.out.println("String is"+ jsonInString);
Output:
String is{"DeviceCommon":{"ASIdentifier":"123","DatadeliveyMechanism":"notify","MobileOriginatorCallbackReference":{"url":"http://application.example.com/inbound/notifications/modatanotification/"},"AccessiblityCallbackReference":{"url":"http://application.example.com/inbound/notifications/accessibilitystatusnotification"}},"DeviceList":[{"ExternalIdentifer":"123456#mydomain.com","msisdn":"123456","senderName":"Device1","MobileOriginatorCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/modatanotification/"},"ConfigurationResultCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/configurationResult"},"ASreferenceID":"AS000001","NIDDduration":"1d"}]}
I need to parse this JSON string to get individual fields like ExternalIdentifier and ASIdentifier.
I tried something like this but it is not working.
JsonObject jobj = new Gson().fromJson(jsonInString, JsonObject.class);
String result = jobj.get("ASIdentifier").toString();
System.out.println("value is"+ result);
Note: ExternalIdentifier is within the array, so I need to loop through the array to find it.
Can you please tell me what I'm doing wrong?
Possible solution:
String result = jobj.get("DeviceCommon").getAsJsonObject().get("ASIdentifier").getAsString();
System.out.println("ASIdentifier: "+ result);
JsonArray jsonArray = jobj.get("DeviceList").getAsJsonArray();
for (JsonElement device : jsonArray ) {
result = device.getAsJsonObject().get("ExternalIdentifer").getAsString();
System.out.println("ExternalIdentifer: "+ result);
}
Output:
ASIdentifier: 123
ExternalIdentifer: 123456#mydomain.com
public static void printJson(JsonElement jsonElement,String key) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
// System.out.println("##key is"+en.getKey() + " : ");
printJson(en.getValue(), en.getKey());
// System.out.println(en.getValue().getAsString());
// System.out.println(jsonElement.getAsString());
}
}
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
System.out.println("###key is"+key);
System.out.println("### value is"+jsonElement.getAsString());
}
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
System.out.println("\n###Array size is"+ jarr.size());
for (JsonElement je : jarr) {
printJson(je,key);
}
}
}
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.
Hello I want to access my web records in my android app. By doing so, I use JSON to do that and PHP. This is the url of my json file: here
But the problem is it's just displaying the php code. I need to be able to access/read that file. :( Any ideas what I am doing in here? Help is much appreciated by me. thanks.
This is what I've tried so far:
<?php
include('connectdb.php');
$sql = "SELECT salesordercard_code, location_from, location_to, salesmancode FROM salesorderingcard";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$set = array();
while($row1 = mysql_fetch_assoc($result)) {
$set[] = $row1;
}
header('Content-type: application/json');
echo json_encode($set);
?>
MainActivity.class
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONFunctions.getJSONfromURL("http://www.shoppersgroup.net/vanmanagement/results.php");
try {
// Locate the array name
jsonarray = jsonobject.getJSONArray("posts");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
//Log.i(MainActivity.class.getName(), jsonobject.getString("movie_name"));
// Retrive JSON Objects
map.put(TAG_CODE, jsonobject.getString("salesordercard_code"));
map.put(TAG_LOCATION_FROM, jsonobject.getString("location_from"));
map.put(TAG_LOCATION_TO, jsonobject.getString("location_to"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
Logcat:
11-18 02:35:08.521: E/log_tag(1047): Error parsing data org.json.JSONException: Value [{"salesmancode":"SLMAN001","location_to":"MAIN","location_from":"IN-TRANSIT","salesordercard_code":"SLESO0001"},{"salesmancode":"SLMAN001","location_to":"MAIN","location_from":"IN-TRANSIT","salesordercard_code":"SLESO0002"}] of type org.json.JSONArray cannot be converted to JSONObject
First as Json String
[ // Its an Array
"posts",// Its not an Array and its index is 0 so we will not use index 0
{//Index1
"salesordercard_code": "SLESO0001",
"location_from": "IN-TRANSIT",
"location_to": "MAIN",
"salesmancode": "SLMAN001"
},
{//index2
"salesordercard_code": "SLESO0002",
"location_from": "IN-TRANSIT",
"location_to": "MAIN",
"salesmancode": "SLMAN001"
}
]
Change your doInBackground() method like below,
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONFunctions.getJSONfromURL("http://www.shoppersgroup.net/vanmanagement/results.php");
try {
// Locate the array name
jsonarray = new JSONArray(jsonobject.toString());
for (int i = 1; i < jsonarray.length(); i++) {// strat from index1
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobj = jsonarray.getJSONObject(i);
//Log.i(MainActivity.class.getName(), jsonobj.getString("movie_name"));
// Retrive JSON Objects
map.put(TAG_CODE, jsonobj.getString("salesordercard_code"));
map.put(TAG_LOCATION_FROM, jsonobj.getString("location_from"));
map.put(TAG_LOCATION_TO, jsonobj.getString("location_to"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
Hope this will solve your problem.
Your results.json file can't run php because it isn't being processed as PHP, its being processed as a json file, and as such it is displaying the text within it as text.
Rename it to results.php and attempt it then, it should print out the json encoded data with the results you need.
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;
}