I have to convert this http post from JavaScript to Android.
I encountered a problem using cids: []. I can't create a jsonobject with this symbol [ ]. It should be an empty array.
This is my JavaScript:
var makeAjaxRequest = function () {
Ext.getBody().mask('Loading...', 'x-mask-loading', false);
var obj = {
uid: 1161,
cids: []
};
Ext.Ajax.request({
url: 'http://test.com.my',
method: 'POST',
params: { json: Ext.encode(obj) },
success: function (response, opts) {
Ext.getCmp('content').update(response.responseText);
Ext.getCmp('status').setTitle('Static test.json file loaded');
Ext.getBody().unmask();
var data = Ext.decode(response.responseText);
Ext.Msg.alert('result::', data.r[1].id, Ext.emptyFn);
}
});
};
This is my Android code:
String[] temp = null;
JSONObject json = new JSONObject();
HttpPost post = new HttpPost(url);
json.put("uid", 1161);
json.put("cids", temp);
List postParams = new ArrayList();
postParams.add(new BasicNameValuePair("json", json.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
tv1.setText(postParams.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
response = client.execute(post);
Using String[] temp = null; isn't right.
Use String[] temp = {};. That denotes an empty array.
I cant create a jsonobject with this symbol "[ ]".
^^That's basically a JSON Array you are trying to create. JSONObjects have {} and JSONArrays have [].
public void writeJSON() {
JSONObject user = new JSONObject();
JSONObject user2;
user2 = new JSONObject();
try {
user.put("dish_id", "1");
user.put("dish_custom", "2");
user.put("quantity", "2");
user.put("shared", "2");
user2.put("dish_id", "2");
user2.put("dish_custom", "2");
user2.put("quantity", "4");
user2.put("shared", "3");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray notebookUsers = new JSONArray();
notebookUsers.put(user);
notebookUsers.put(user2);
System.out.println("the JSON ARRAY is"+notebookUsers);
Will give a JSON array of user and user2 with symbols "[]"
Related
I have problem with reading json attribute even though object correctly instanced.
First, I send json from client side with JavaScript:
let object = {
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
email: document.getElementById("email").value,
action: "registration"
}
let request = new XMLHttpRequest();
...
On server side I have code:
req.setCharacterEncoding("UTF-8");
JSONObject jsonObject = null;
// String address = "/WEB-INF/pages/login.jsp";
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
/* report an error */ }
try {
jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
String action = jsonObject.getString("firstName");
jsonObject exists but program throws org.json.JSONException: JSONObject["firstName"] not found.
Object on server side when I use debugger:
There is no key with a name like firstName in your jsonObject. Instead, you need to search for Method property and then parse the firstName from it. First, declare a GetQueryMap method:
public static Map<String, String> GetQueryMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String [] p=param.split("=");
String name = p[0];
if(p.length>1) {
String value = p[1];
map.put(name, value);
}
}
return map;
}
Then use it like:
String method = jsonObject.getString("Method");
Map params = GetQueryMap(method);
String firstName = (String)params.get("firstName");
String lastName = (String)params.get("lastName");
I think the issue is that you're not sending the data correctly from the browser side.
are you sending the correct content-type header (application/json)?
Are you serializing the object correctly for sending?
I have converted array of object into json string in jsp as follows
$("#submitButton").click(function(){
var sample = new Array();
var k = 1;
for(var i=0; i < JSONObj.length; i++){
var remarkString = $("#eduRemark"+k).val();
var scoreNum = $("#eduScore"+k).val();
var objectInfo = {"iqrQuestionRemark":remarkString, "iqrQuestionScore":scoreNum,"crtnByUmId":""};
sample.push(objectInfo);
k++;
}
var ArrayData = JSON.stringify(sample);
alert("Json Data:"+ArrayData);
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/Vidyasaarathi/ipusers/submitAssessmentform",
data: ArrayData,
success :function(result) {
}
});
});
The ajax call works fine. At controller side i'm getting list of object as String. in following format
[{"iqrQuestionRemark":"nitin","iqrQuestionScore":"10","crtnByUmId":""},{"iqrQuestionRemark":"akash","iqrQuestionScore":"12","crtnByUmId":""},{"iqrQuestionRemark":"sharad","iqrQuestionScore":"14","crtnByUmId":""}]
Now my question is how to iterate this array of object individually at controller side.
Here is my controller code
#RequestMapping(value={VspCommonConstants.INTERVIEW_PANEL_MANAGER_URL+"/submitAssessmentform"}, method = RequestMethod.POST)
public String submitAssessmentform(#RequestBody List<InterviewQuestionResult> ArrayData,HttpServletRequest request,Model model) throws JsonParseException, JsonMappingException, IOException
{
ObjectMapper mapper = new ObjectMapper();
//String [] actualData = mapper.readValue(ArrayData, String[].class);
//System.out.println("Json converted Data:"+actualData);
System.out.println("Result object:"+ArrayData);
String view = null;
try {
view = "ipsearchForm";
} catch (Exception e) {
model.addAttribute("errormsg", "System is busy...... Please try after some time.");
}
return view;
}
Please suggest some possible way. Here i'm trying to assign json string to 'InterviewQuestionResult' bean which has a getter setter. Thanks in advance.
I have 3 JSONArrays and JSonobject that I want to return as success response in ajax.
I have created
out.print(jarrayTable);
out.print(jarrayChartTotalMF);
out.print(jarrByAgeGroup);
out.print(objTotal);
I dont know how to get the data in ajax - jquery. I tried to run the program with one JSONArray and it perfectly works but
i dont know how to create multiple arrays and a object and parsing them into jquery variables in return success of ajax.
I also tried to do this, but i dont know how to parse the data in jquery
String json1 = new Gson().toJson(jarrayTable);
String json2 = new Gson().toJson(objTotal);
String json3 = new Gson().toJson(jarrayChartTotalMF);
String json4 = new Gson().toJson(jarrByAgeGroup);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String AllJson = "[" + json1 + "," + json2 + "," + json3 + "," + json4 + "]"; //Put both objects in an array of 2 elements
response.getWriter().write(AllJson);
I am currently getting this reults, how do i get the data in jquery
[{"ByAgeGroupSexTable":[{"BothSexes":42,"AgeGroup":"Under 1","ApprovedBy":"Geraldine Atayan","Male":25,"Female":17,"location":"Barangay 1","UploadedBy":"Shermaine Sy"},{"BothSexes":42,"AgeGroup":"Under 1","ApprovedBy":"Geraldine Atayan","Male":25,"Female":17,..."arrByAgeGroup":[{"arrByAgeGroupBothSexes":0,"arrByAgeGroupMale":25,"arrByAgeGroupFemale":17,"arrByAgeGrouplocation":"Barangay 1","arrByAgeGroupAgeGroup":"Under 1"},{"arrByAgeGroupBothSexes":0,"arrByAgeGroupMale":25,"arrByAgeGroupFemale":17,"arrByAgeGrouplocation":"Barangay...
this is what i get when i print it out on console by using console.log(JSON.stringify(data)); but when i try to get the variable/data console.log("HELLO" +print[0].ByAgeGroupSexTable[0].location); this was the error Cannot read property '0' of undefined
This is my JS code
$("#archived tbody").on("click", 'input[type="button"]', (function () {
var censusYear = $(this).closest("tr").find(".nr").text();
alert(censusYear);
var page = document.getElementById('page').value;
$.ajax({
url: "SetDataServlet",
type: 'POST',
dataType: "JSON",
data: {
censusYear: censusYear,
page: page
},
success: function (data) {
console.log(JSON.stringify(data));
var print = JSON.stringify(data);
console.log("HELLO" +print[0].ByAgeGroupSexTable[0].location);
...some other codess
}, error: function (XMLHttpRequest, textStatus, exception) {
alert(XMLHttpRequest.responseText);
}
});
}));
You could try like this. I don't know what kind of Objects have been pushed in those arraylist.
ArrayList<Object> allList = new ArrayList<>();
ArrayList<Object> jarrayTable = new ArrayList<Object>();
ArrayList<Object> jarrayChartTotalMF = new ArrayList<Object>();
ArrayList<Object> jarrByAgeGroup = new ArrayList<Object>();
JsonObject objTotal= new JsonObject();
allList.add(objTotal);
allList.add(jarrayTable);
allList.add(jarrayChartTotalMF);
allList.add(jarrByAgeGroup);
String allJSON = new Gson().toJson(allList);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
se.getWriter().write(allJSON);
output1 :
[{},[],[],[]]
Or
HashMap<String, Object> allList = new HashMap();
ArrayList<Object> jarrayTable = new ArrayList<Object>();
ArrayList<Object> jarrayChartTotalMF = new ArrayList<Object>();
ArrayList<Object> jarrByAgeGroup = new ArrayList<Object>();
JsonObject objTotal= new JsonObject();
allList.put("obj", objTotal);
allList.put("arr1",jarrayTable);
allList.put("arr2",jarrayChartTotalMF);
allList.put("arr3",jarrByAgeGroup);
String allJSON = new Gson().toJson(allList);
output2
{"obj":{},"arr2":[],"arr1":[],"arr3":[]}
This line
var print = JSON.stringify(data); //just remove JSON.stringify()
Converts your object to a string so you can not access it. You can easily access the object now
$("#archived tbody").on("click", 'input[type="button"]', (function () {
var censusYear = $(this).closest("tr").find(".nr").text();
alert(censusYear);
var page = document.getElementById('page').value;
$.ajax({
url: "SetDataServlet",
type: 'POST',
dataType: "JSON",
data: {
censusYear: censusYear,
page: page
},
success: function (data) {
console.log(JSON.stringify(data));
var print = data;
console.log("HELLO" +print[0].ByAgeGroupSexTable[0].location)
}, error: function (XMLHttpRequest, textStatus, exception) {
alert(XMLHttpRequest.responseText);
}
});
}));
This is my POST request:
$scope.TestPost = function (par1, par2) {
$http.post('EmployeeService.asmx/GetAllEmployees',
{
par1: par1,
par2: par2
})
.then(function (response) {
$scope.employees = response.data;
})
};
And this is code that gets called on the server side. Code is called correctly and json serialized object is written to response:
[WebMethod]
public void GetAllEmployees(string par1, string par2)
{
List<Employee> listEmployees = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
List<Employee> _list = new List<Employee>();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblEmployees", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
Employee emp = new Employee
{
id = Convert.ToInt32(rdr["Id"]),
name = rdr["Name"].ToString(),
gender = rdr["Gender"].ToString(),
salary = Convert.ToInt32(rdr["Salary"])
};
listEmployees.Add(emp);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listEmployees));
}
Response object is this - some strange line is appended at the end {"d":null} which I can not understand why. I am also receiving error on the client side: SyntaxError: Unexpected token:
"[{"id":1,"name":"Ben","gender":"Male","salary":55000},
{"id":2,"name":"Sara","gender":"Female","salary":68000},
{"id":3,"name":"Mark","gender":"Male","salary":57000},
{"id":4,"name":"Pam","gender":"Female","salary":53000},
{"id":5,"name":"Todd","gender":"Male","salary":60000}]{"d":null}"
Thanks to #82Tuskers and this post:
Differences between Response.End() and Response.Flush()
I've found the solution. I've changed code at the end of server side function to:
Context.Response.Clear();
Context.Response.Write(js.Serialize(listEmployees));
Context.Response.Flush();
Context.Response.End();
Response is now OK.
//IService.cs
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
String CheckAuth(String AccountID, String Password);
//Service.cs
public String CheckAuth(String AccountID, String Password)
{
String message="";
string StrCon = #"my conn string";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(StrCon);
string qry = "select * from Account where AccountID='" + AccountID + "' and Password='"+Password+"'";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
message = "Authorized";
}
else
{
message = "unauthorized";
}
con.Close();
return message;
}
i want to know that what does the variable d: stands for and how can i change the d: to Message:..??
i need some suggestion thank you..
//GETTING output
{
d: "Authorized"
}
//expected output
{
Message: "Authorized"
}
i m new to wcf so it will be helpful if i get undertandable suggestion
thank you..
The variable d is there for security reasons.
But you can always return an object instead of a string
public object CheckAuth(String AccountID, String Password)
{
// .. snip
return new {
Message = message
};
}
If you call your service like this, it should return something like
{
"d" : {
"Message": "Authorized"
}
}
Not sure what you're using on the front-end, if you use jQuery you could make a wrapper around the ajax function:
function doAjax(url, data, cb) {
$.ajax({
url: url,
data: data,
success: function(data) {
cb(data.d);
}
});
}
and make use of your new defined function like this:
doAjax('/CheckAuth', yourDataObj, function result(data) {
console.log(data.Message);
});