How do I convert JsonResult to a model in MVC.NET? - json

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);
}

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()

Xamarin store multiple data in Variable

I have my code, where i fetch data from a url and parse that data with json.
public async void GetItems()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpClient httpclient = new HttpClient();
Uri uri = new Uri("URL");
response = await httpclient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var JsonContent = await response.Content.ReadAsStringAsync();
JArray jArray = JArray.Parse(JsonContent);
foreach (var data in jArray)
{
var latitude = data["latitude"];
Console.WriteLine(latitude);
}
}
}
in this code I get all my data and print them into the console.
I have a class with the variables i want to set
public class FetchedObjects
{
public string name { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
}
How can I store each data from my jArray into these variables? I want to have access to these from my ios or android project.
EDIT
I have some values in json, which are null. How can i handle these, while creating the list? My App crashes, it says :
Error setting value to 'valuename' on 'App.FetchedObjects'
Try it code:
List<FetchedObjects> list = jArray.ToObject<List<FetchedObjects>>();
Edit
in pcl library create class:
public class YourClass
{
public async Task<List<FetchedObjects>> GetItems()
{
....
if(jArray != null)
{
List<FetchedObjects> list = jArray.ToObject<List<FetchedObjects>>();
return list;
}
else
{
return null;
}
...
}
Add reference to pcl library in your ios and android projects and Use class YourClass

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 !!!
}

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;

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.