how to Deserialize Json response from WCF Restful Service? - json

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;

Related

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 do I convert JsonResult to a model in MVC.NET?

I am trying to convert JsonResult object to a model.
I've seen few example which converts Json strings to model, but wasn't quite sure how I would convert JsonResult object.
I was trying to use ConvertToType but wasn't successful.
What am I doing wrong?
public ActionResult Search(string keyWord)
{
var result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = _featuresSearch.Search(keyWord)
};
JavaScriptSerializer objJavascript = new JavaScriptSerializer();
_SearchResult model = objJavascript.ConvertToType<_SearchResult>(result);
return View("SearchResult", model);
}

parsing boolean value with 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 !!!
}

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:

Not Getting the Root Name in JSON Format using WCF Rest

I am not getting any root value of the Json Format.
I am getting the response as follows:
[{"Username":"demo","UserID":8,"Password":"demo","EmaiID":"demo#gmail.com"}]
I would like to have the format as follows
{UserList: [[{"Username":"demo","UserID":8,"Password":"demo","EmaiID":"demo#gmail.com"}]}
Service Declaration :
public interface IDemo
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,ResponseFormat =
WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/Validate", Method = "POST")]
Stream ValidateUser(Login obj);
}
[DataContract]
public class Login
{
public Login()
{
}
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
}
Service Definition :
public class Demo: IDemo
{
string Json = string.Empty;
JavaScriptSerializer obj1 = new JavaScriptSerializer();
public Stream ValidateUser(Login obj)
{
UserList objUserList = new UserList();
Users objUser = new Users();
objUser.Username = obj.Username;
objUser.Password = obj.Password;
objUserList = LoginDataService.ValidateUser(objUser.Username,objUser.Password) ;
if (objUserList.Count > 0)
{
Json = obj1.Serialize(objUserList);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/json; charset=utf-8";
}
else
{
UserError objError = new UserError();
objError.ErrMsg = "LoginFailed";objError.Username = objUser.Username ;
Json = obj1.Serialize(objError);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/json; charset=utf-8";
}
return new MemoryStream(Encoding.UTF8.GetBytes(Json));
}
}
Can anyone help me to get the result with root element and let me know what kind of mistake i have done.
Thanks & Regards,
Vijay
You are getting the format like that since you are serializing a collection into JSON. You can return a class that wraps the list inside as a property then you will get what you desire.
For ex. you can create a class like this
public class UserListResponse
{
public UserList UserList{get; set;}
}
Now you get the JSON as what you expected, like
{UserList:[..]}
I don't understand why you are returning a Stream and doing yourself all the serialization framework, basically this all done by the framework. All you have to do is return the wrapper class UserListResponse from the service method.
public class Demo: IDemo
{
public UserListResponse ValidateUser(Login obj)
{
...
return new UserListResponse{ UserList = objUserList};
}
}
The WCF will take care of returning the structure into JSON or XML and you don't need to worry about that.
While the above solution perfectly works you can also try using paramter BodyStyle=WebMessageBodyStyle.WrappedResponse of WebInvoke attribute on your method.
This wraps the values in type name.