parsing boolean value with Json - json

I'm using json to send objects from Android application to Web Api application.
When i try to send an object which contains boolean value its value will be deserialized into false even if its true in json !
Here is an exemple :
public class myObject{
public boolean value1;
public String value2;
}
And I have this method to my object to the server :
public String PostObject(String url, Object obj) throws ParseException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create().toJson(obj));
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String resp = EntityUtils.toString(httpEntity);
return resp;
}
And finally here I'm sending my object to the server :
myObject obj = new myObject();
obj.value1 = true;
obj.value2 = "testing";
JSONHttpClient jsonHttpClient = new JSONHttpClient();
String response = jsonHttpClient.PostObject(myURL, obj);
And here my code from server side :
[AcceptVerbs("POST")]
public string test(myObject obj)
{
//obj.value1 = false !!!
}

Related

While automating Get call,why do we have to convert the http entity into string and then to a JSON Object,before accessing it?

Here is a code snippet i came across one of the youtube tutorials for api automation using rest assured:
public class getCallTest extends testBase {
public testBase testbase;
public String endpoint;
public String serviceurl;
public String uri;
public CloseableHttpResponse httpresponse;
public HttpEntity httpentity;
public RestClient restclient;
public String entitybody;
#BeforeMethod
public void setUp() {
testbase = new testBase();
endpoint = prop.getProperty("endpointurl");
serviceurl = prop.getProperty("serviceurl");
uri = endpoint + serviceurl;
System.out.println(uri);
}
#Test
public void getCall() {
// fetching status code from the http response
restclient = new RestClient();
try {
httpresponse=restclient.getCall(uri);
} catch (Exception exception) {
exception.getMessage();
exception.printStackTrace();
}
int statuscode = httpresponse.getStatusLine().getStatusCode();
System.out.println("Http response code is :" + statuscode);
// fetching the http entity(this http entity will have entity header and entity
// body)
httpentity = httpresponse.getEntity();
try {
entitybody = EntityUtils.toString(httpentity);
} catch (Exception exception) {
System.out.println("Some exception occurred while converting http entity to string");
exception.getMessage();
exception.printStackTrace();
}
// convert the entitybody json string to json object
JSONObject jsonresponse = new JSONObject(entitybody);
System.out.println(jsonresponse);
After fetching the response entity using getEntity(),why do we need to cconvert it into string using EntityUtils.toString() and then to a JSON object ?

Get Access token genertaed from JSON in SpringBoot Application

#RequestMapping(value = "/check", method = RequestMethod.GET)
public ResponseEntity<Product> createProducts() throws JsonProcessingException {
String reqUrl = "http://localhost:8080/home";
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> bodyParamMap = new HashMap<String, String>();
bodyParamMap.put("grant_type", "K1");
bodyParamMap.put("client_id", "K2");
bodyParamMap.put("client_secret", "sjxjkdcnjkk");
String reqBodyData = new ObjectMapper().writeValueAsString(bodyParamMap);
HttpEntity<String> requestEnty = new HttpEntity<>(reqBodyData, headers);
ResponseEntity<Product> result = restTemplate.postForEntity(reqUrl, requestEnty, Product.class);
return result;
}
I am geeting a JSON response form result which have access_token which I want to get.
I tried using JSONObject but it is not working. How Can I fetch the value of access_token
JSONObject jsonObject = JSONObject.fromObject(result.toString());
String m = jsonObject.get("access_token").toString();
I tried using this but it is showing compile time error
My output is accepted as
{"access_token":"ghdjhdjhhh","expires_in":2300}
I want to fetch this access_token
when you use postForEntity your Product.class is suppose to represent your result (responseType), so if your converters are well defined(normally the spring boot default ones are sufficient for json) with your class Product looking like this
public class Product {
#JsonProperty("access_token")
private String accessToken;
#JsonProperty("expires_in")
private Long expiresIn;
public String getAccessToken() {
return accessToken;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
}
then you can get your result like this
ResponseEntity<Product> result = restTemplate.postForEntity(reqUrl, requestEnty, Product.class);
Product product = result.getBody();
String token = product.getAccessToken()

How can I send a JSON string request or post in the webservice with authorization header using volley?

I have a previous code for connecting to a webservice using httpclient. String entity it is working with no problem. I want to update it using volley. I tried the below code but it gives me unexpected, BasicNetwork.performRequest: Unexpected response code 400.
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("{\"LoginDate\":\"\\/Date(" + today.getTime() + "+0800)\\/\",\"MAC\":\"00-00-00-12-12-12\",\"MerchantID\":\"xxxxx\",\"StationName\":\"WKSTN01\",\"UserName\":\"exampleuser\"}");
}catch (Exception e) {
e.printStackTrace();
}
Log.e("JSONOBEJCT", jsonObject.toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonObject , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("Response", jsonObject.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", messageHasValue);
return headers;
}
};
This is my old code and I just want to update it with volley, is there any way I can do it?...
StringEntity entity = new StringEntity(object.toString());
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
entity.setContentType("application/json");
httpPost.addHeader("Authorization", messageHasValue);
httpPost.setEntity(entity);
Log.e("HTTPPOST ", httpPost.toString());
HttpResponse response = client.execute(httpPost);
HttpEntity resEntity = response.getEntity();
Its working now, I tried to upgrade my PHP version from 4 to 5 and format the TimeStamp.

Sending data by JSON

I want to send JSON from desktop application to the server with mvc wepApi.
this is my desktop application code ,that convert data to the JSON and send it.
private void btnAddUserType_Click(object sender, EventArgs e)
{
UserType userType = new UserType();
userType.UserTypeName = txtUserTypeName.Text;
string json = JsonConvert.SerializeObject(userType);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
}
and this is my web api
// POST api/default1
public void Post([FromBody]string value)
{
UserTypeRepository bl = new UserTypeRepository();
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserType));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
UserType u = new UserType();
u = (UserType)js.ReadObject(stream);
bl.Add(u);
}
but when post api is calling the Value is null.
why?
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
You are not flushing nor closing the stream, so basically the data never gets to the api.
My code:
Program.cs - Console App
class Program
{
static void Main(string[] args)
{
var user = new UserModel {Id = 4, FirstName = "Michael", LastName = "Angelo"};
var json = JsonConvert.SerializeObject(user);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:56506/api/Values/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
UserModel.cs - some data class
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
}
ValuesController.cs - WebApi controller from template
public class ValuesController : ApiController
{
// GET api/values
public UserModel[] Get()
{
return UserProvider.Instance.Get(); // returns some test data
}
// GET api/values/5
public UserModel Get(int id)
{
return new UserModel{Id=1,FirstName="John",LastName="Smith"};
}
// POST api/values
public void Post([FromBody]UserModel value)
{
if (value == null) // BREAKPOINT HERE, just to see what's in value
{
var x = value;
}
}
}
WebApiConfig.cs - default config with added line about Json, but IT WORKS WITHOUT IT -it's so that I can test GET easily in browser etc. ;)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Result:

how to Deserialize Json response from WCF Restful Service?

I want to deserialize a Json response into my class object. I have created a WCF Restful Service, and from client using proxy object I'm calling a service method which return me a json. Now I want to convert that json into my class object.
My service is as follow:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "GetProject/{projectID}")]
tblProject GetProject(String projectID);
Implementations:
public tblProject GetProject(String projectID)
{
tblProject pro = new tblProject();
pro = DAL.ProjectDAL.GetProject(Convert.ToInt32(projectID));
return pro;
}
and from controller in MVC I'm making request as:
public ActionResult Index()
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost:8733/Design_Time_Addresses/RestServiceLibrary.RESTService/REST_ProjectService/getproject/2");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string txtResult = reader.ReadToEnd();
return view();
}
and when I run I'm getting response as:
and when I call through a proxy method I got exception:
but my endpoints are there in config as,
you can use javascriptserializer
string s = "YouJsonText";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(s);
//or
YouCustomClass res = serializer.Deserialize<YouCustomClass>(sb.ToString());
Also, you can use CustomJsonConverter like this:
public class YouCustomClassConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
//and first you need register type, which you want Deserialize
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(YouCustomClass ) }; }
}
}
//and then example of using JavaScriptSerializer with custom converter
var ser = new JavaScriptSerializer();
ser.RegisterConverters(new JavaScriptConverter[] { new YouCustomClassConverter() });
try
{
YouCustomClass obj = ser.Deserialize(jsonString);
}
Note: you need use using System.Web.Script.Serialization;
class GetProjectResultWrapper
{
public GetProjectResult GetProjectResult{ get; set; }
}
class GetProjectResult
{
public string id {get;set;}
.....
......
}
JavaScriptSerializer ser = new JavaScriptSerializer();
GetProjectResultWrapper response = ser.Deserialize<GetProjectResultWrapper>(sb.ToString());
response .GetProjectResult;