Here i am calling servlet through AJAX Call from JSP.In servlet ,fetching data from DB and Converting these data to JSON Format using Gson.After that i want to send this json object to this JSP.But here i am not able to send json object.Please suggest Me?
Here code for AJAX Call :
<script type="text/javascript">
$(document).ready(function() {
$('#subbtn').click(function(event) {
console.log("Hello");
var searchfield = $('#searchfields').val();
var operator = $('#operator').val();
var fieldvalue = $('#searchstring').val();
var filter=searchfield+operator+"'"+fieldvalue+"'";
console.log(filter);
$.get('SearchData', {
filter : filter
}, function(responseText) {
$('#example').html(responseText);
console.log('dddd');
});
});
});
</script>
Here is servlet COde :
String query = "select * from searchsample";
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
renderingengine = resultSet.getString("RenderingEngine");
browser = resultSet.getString("Browser");
platform = resultSet.getString("platform");
engineversion = resultSet.getString("EngineVersion");
cssgrade = resultSet.getString("CSSGrade");
}
Gson gson = new Gson();
JsonVo jsondata=new JsonVo();
jsondata.setRenderingengine(renderingengine);
jsondata.setBrowser(browser);
jsondata.setPlatform(platform);
jsondata.setEngineversion(engineversion);
jsondata.setCssgrade(cssgrade);
String toJson = gson.toJson(jsondata);
System.out.println("Json Format : " +toJson);
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
I think you just need write below line to send JSON to JSP from servlet.
response.setContentType("application/json");
response.getWriter().write(toJson);
Related
I used to do a post request using native C#'s library
var httpWebRequest = (HttpWebRequest)WebRequest.Create(djangoApi + user);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"wallet_id\":\""+wallet+"\"," +
"\"token\":\"foo\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
but that doesn't work on mobile. So, I need to use UnityWebRequest
Following the example, https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html, my functions look almost identical. Here is the coroutine function
IEnumerator SendPostCoroutine()
{
WWWForm form = new WWWForm();
form.AddField("user_id", "0x241477cE189fa014292d99e0807cB449b878");
form.AddField("token", "foo");
using (UnityWebRequest www = UnityWebRequest.Post(djangoApi + user, form))
{
Debug.Log(www.downloadHandler.text);
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("POST successful!");
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> dict in www.GetResponseHeaders())
{
sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
}
// Print Headers
Debug.Log(sb.ToString());
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
}
}
}
When I do
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
neither prints out the body of the object I want. Instead, all I get is
<!DOCTYPE html>
<html lang="en">
What can I do to get the values within the json?
I just used
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
Debug.Log("Status Code: " + request.responseCode);
}
taken from https://forum.unity.com/threads/posting-json-through-unitywebrequest.476254/. That way, I can post my raw json
Hello I have created a RESTful web services which returns the responce in below format :
[
{"empId":1,"empName":"A"},
{"empId":2,"empName":"B"},
{"empId":3,"empName":"C"},
{"empId":4,"empName":"D"},
{"empId":5,"empName":"E"}
]
I have written the simple visualforce page to call the method named 'lookup' on button click action. My Apex class is given below.
public class REST {
public PageReference lookup()
{
string resp;
// Note this version of the API is only for the US
string endpoint ='http://localhost:8080/RESTfulExample/rest/json/metallica/get';
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setMethod('GET');
req.setEndpoint(endpoint);
try {
res = http.send(req);
} catch (Exception e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
return null;
}
resp = res.getBody();
JSONParser parser = JSON.createParser(resp);
// Parsing The JSON & set the list of values to the variables 'empid' & 'empname'
return null;
}
}
Can anyone help me how I can use JSON parser to parse the JSON and to store the values to the variables.
Thank You !!!
If you would like to use JSONParser here is an example from the Salesforce documentation on JSONParser(https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsonparser.htm):
public class JSONParserUtil {
#future(callout=true)
public static void parseJSONResponse() {
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'https://docsample.herokuapp.com/jsonSample';
request.setEndPoint(endpoint);
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
HttpResponse response = httpProtocol.send(request);
System.debug(response.getBody());
/* The JSON response returned is the following:
String s = '{"invoiceList":[' +
'{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
'{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
'"invoiceNumber":1},' +
'{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
'{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
'{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
']}';
*/
// Parse JSON response to get all the totalPrice field values.
JSONParser parser = JSON.createParser(response.getBody());
Double grandTotal = 0.0;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'totalPrice')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
grandTotal += parser.getDoubleValue();
}
}
system.debug('Grand total=' + grandTotal);
}
}
Although from what you say in your question I think it would be simpler to do JSON Deserialization.
Here is an example on how to do it:
Wrapper Class
public class EmployeeWrapper {
public Integer empId {get;set;}
public String empName {get;set;}
}
JSON Deserialization
String jsonContent = '[{"empId": 1,"empName": "A"}, {"empId": 2,"empName": "B"}, {"empId": 3,"empName": "C"}, {"empId": 4,"empName": "D"}, {"empId": 5,"empName": "E"}]';
List<EmployeeWrapper> employeeWrapperList = (List<EmployeeWrapper>)JSON.deserialize(jsonContent, List<EmployeeWrapper>.class);
System.debug(employeeWrapperList);
//Do actions to WrapperList
JsonConvert.DeserializeObject<> not working .
Always getting null.
Json.NET deserializing object returns null.
Here is the code:
JsonResult jsonresult = Json(result1, JsonRequestBehavior.AllowGet);
User _contacts = new User();
_contacts = JsonConvert.DeserializeObject<User>(jsonresult.Data.ToString());
In jsonresult.Data.ToString():
{"recordsTotal":13,"recordsFiltered":13,"data":[{"Id":2,"Title":"Brajo testing","Type":null,"Description":null,"Importancy":null,"CreatedDate":"2017-03-16T14:31:04.41","Status":null,"Email":"+HNcbJGxLqAGmAQq9gOW1A==","Name":"Oliver Woodss"},{"Id":3,"Title":"udal testing","Type":null,"Description":null,"Importancy":null,"CreatedDate":"2017-03-16T14:31:41.253","Status":null,"Email":"+HNcbJGxLqAGmAQq9gOW1A==","Name":"Oliver Woodss"},
When i assign this comes null.
result = this.Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = _contacts }, JsonRequestBehavior.AllowGet);
Do like this,
var response = client.GetAsync(apiUrl).Result;
var responseResult = JsonConvert.DeserializeObject<List<User>>
(response.Content.ReadAsStringAsync().Result);
Then you can fetch data from responseResult with a dot operator.
So i am working this project on Xamarin forms, and get the error as in title on
var rootObject = deserial.Deserialize<RootObject>(gameJson);
I am supposed to return the list of games to my app.How can i remove the error?
public async Task<Game[]> GetGamesAsync(){
var client = new RestClient("http://mystore/");
var request = new RestRequest ("api/Games", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var apiKey = session ["ApiKey"];
var userId = session ["UserId"];
try
{
request.AddHeader ("authenticationkey",apiKey.ToString ());
request.AddHeader ("authenticationid",userId.ToString ());
}
catch{}
IRestResponse response = client.Execute (request);
statusCodeCheck (response);
var gameJson = response.Content;
if (response.StatusCode == HttpStatusCode.OK) {
RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer ();
var rootObject = deserial.Deserialize<RootObject>(gameJson);
return rootObject.games;
}
else if(response.StatusCode == HttpStatusCode.Forbidden){
return null;
}
}
Not sure you are looking for this but I also using Restsharp in portable library and I'm deserializing datacontracts with Json.NET's JsonConvert.DeserializeObject<T>
method. I have not encountered any problem with it yet.
Also another possible solution is that the returned data is wrapped and the main object is not the RootObject.
string URL="https://sampleservicebus.servicebus.windows.net/WinPhoneService/"
RestClient client = new RestClient(URL);
RestRequest request = new RestRequest("getkpimeasuredata", Method.POST);
KpiDomainData kpidata = new KpiDomainData();
kpidata.KPIId = 1006;
kpidata.ScorecardId = 3;
kpidata.EngineeringOrgId = 11;
kpidata.DataValuetypeId = 1;
kpidata.CumulativeMonth = 463;
kpidata.BusinessOrgId = 1;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(kpidata);
json = "{\"kpidata\" : " + json + "}";
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
ObservableCollection<KpiMeasureData> kpiDetailsList = await client.ExecuteTaskAsync<ObservableCollection<KpiMeasureData>>(request);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
}
});
When I debugged the wcf service code i came to know that the json data sent to getkpimeasuredata webmethod is null, I mean all the property values of the composite type were null even though I'm passing the data with values
And the Restcall works when I use Webclient instead of Restclient. But I need to use Restclient only. Please help.