I convert json to object and get this error
Newtonsoft.Json.JsonSerializationException: 'Error converting value "{"mid":"2","phone":"0965403801","requestId":"1585970510.732827","bankHubToken":"eyJ0aW1lc3RhbXAiOiIxNjMzNDE4NzgyNzQ0IiwidG9rZW4iOiI5NWJmYWM3OC00YmY3LTQyM2MtYjAxNS00NTNjMjkzYzk1ZWEiLCJzaWduIjoiLzVrcTg2dWdReFUvQ1daWCt2TERSaGhvaXN1VC9hS1JpejEwUGtTU0dxUVx1MDAzZCJ9","userName":"1392H46"}" to type 'OBBE.DGBIZ.API.Model.DataFieldUploadFile'. Path '', line 1, position 305.'
my code
var data = context.ActionArguments["data"];
if (data == null)
{
context.Result = new OkObjectResult(
new ErrorResponseMessage() { context = new ContextResponse(false, new List<string>() { APPID, HANDER_ERRORCODE.ERR_REQUEST_CONTENT.ToString(), "Request null" }, new ContextRequest("", ""), ResultConstants.ERROR_CODE_FAIL, "Request null") });
return;
}
try
{
String x = JsonConvert.SerializeObject(data);
data = JsonConvert.DeserializeObject<DataFieldUploadFile>(JsonConvert.SerializeObject(data));
}
and my class
public class DataFieldUploadFile
{
public String? mid { get; set; }
public String? requestId { get; set; }
public String? phone { get; set; }
public String? bankHubToken { get; set; }
public String? userName { get; set; }
}
I try but not OK.
try this
DataFieldUploadFile data = context.ActionArguments["data"] as DataFieldUploadFile;
if data is null it means that data is a probably a json string already, and try to double serialize it.
So you really need this code
string json = context.ActionArguments["data"]?.ToString();
if (!string.IsNullOrEmpty(json))
{
var data = JsonConvert.DeserializeObject<DataFieldUploadFile>(json);
}
else ... you another code
Related
I want custom object in response of API having [required] data annotation on model properties like this:
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "fatal",
"code": "required",
"location": [
"/f:AllergyIntolerance/f:status"
]
}
]
}
Is it possible to do it or I would have to code it.
Because model validation happens before action is called, is there any way I can do it?
To create custom request and respond samples for your api, you can use Swashbuckle.AspNetCore.Swagger and to improve validations on your models you can use FluentValidations Sample. Good Luck!
first for simplify define your models like these :
public class ResponseModel
{
public string resourceType { get; set; }
public List<ResponseIssueModel> issue { get; set; } = new List<ResponseIssueModel>();
}
public class ResponseIssueModel
{
public string severity { get; set; }
public string code { get; set; }
public List<string> locations { get; set; } = new List<string>();
}
Then on your actions you can return this :
var response = new ResponseModel();
response.resourceType = "OperationOutcome";
response.issue.Add(new ResponseIssueModel
{
severity = "fatal",
code = "required",
locations = { "/f:AllergyIntolerance/f:status" }
});
return Ok(response);
you can use Builder Pattern for easy create response object
If you want to validate your model in controller,you could try with TryValidateModel method as mentioned in the document:
I tried as below:
in controller:
var model = new TestModel() { Id=1,nestedModels=new List<NestedModel>() { new NestedModel() { Prop1="P11"} } };
var isvalid=TryValidateModel(model);
var errorfiledlist = new List<string>();
if (!isvalid)
{
foreach (var value in ModelState.Values)
{
foreach (var error in value.Errors)
{
errorfiledlist.Add(MidStrEx(error.ErrorMessage,"The "," field"));
}
}
}
var jsonstring = JsonSerializer.Serialize(model);
foreach (var field in errorfiledlist)
{
var oldstr = String.Format("\"{0}\":null", field);
var newstr = String.Format("\"{0}\":\"required\"", field);
jsonstring = jsonstring.Replace(oldstr, newstr);
};
var obj = JsonSerializer.Deserialize<Object>(jsonstring);
return Ok(obj);
MidStrEx method:
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
}
return result;
}
Models:
public class TestModel
{
public int Id { get; set; }
[Required]
public string Prop { get; set; }
public List<NestedModel> nestedModels { get; set; }=new List<NestedModel>();
}
public class NestedModel
{
public string Prop1 { get; set; }
[Required]
public string Prop2 { get; set; }
}
The result:
I'm having trouble loading this json object into an array.
Here is a snippet (fragment) of my JSON response from the API:
{
"count":192,
"value":[
{
"id":"03dd9f56-108f-4e8f-b92e-93df05717464",
"name":"IIBTest",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/03dd9f56-108f-4e8f-b92e-93df05717464",
"state":"wellFormed",
"revision":14434848,
"visibility":"private",
"lastUpdateTime":"2016-08-19T12:21:37.187Z"
},
{
"id":"b7e15034-fc8f-4f7e-866a-cb06f44b12ed",
"name":"MS Project POC",
"description":"POC for MS Project with TFS",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/b7e15034-fc8f-4f7e-866a-cb06f44b12ed",
"state":"wellFormed",
"revision":14434955,
"visibility":"private",
"lastUpdateTime":"2017-10-03T19:31:56.56Z"
},
{
"id":"59e06621-c5f5-4fd1-9c55-1def541b99d9",
"name":"WorkflowReporting",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/59e06621-c5f5-4fd1-9c55-1def541b99d9",
"state":"wellFormed",
"revision":14434591,
"visibility":"private",
"lastUpdateTime":"2015-09-11T06:59:12.21Z"
},
{
"id":"78a802f0-5eee-4bcb-bde9-a764e46f56db",
"name":"iSolutions",
"description":"",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/78a802f0-5eee-4bcb-bde9-a764e46f56db",
"state":"wellFormed",
"revision":14435476,
"visibility":"private",
"lastUpdateTime":"2021-08-05T17:17:26.193Z"
},
{
"id":"1f20506a-63a5-486a-a857-fec64d7486a6",
"name":"Training",
"description":"MLITS Training and Learning",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/1f20506a-63a5-486a-a857-fec64d7486a6",
"state":"wellFormed",
"revision":14435350,
"visibility":"private",
"lastUpdateTime":"2021-04-08T22:48:02.923Z"
},
...
}
And here is my code:
public class Rootobject
{
public int count { get; set; }
public Value[] value { get; set; }
}
public class Value
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public string state { get; set; }
public int revision { get; set; }
public string visibility { get; set; }
public DateTime lastUpdateTime { get; set; }
public string description { get; set; }
}
static void Main(string[] args)
{
var client = new RestClient("https://devops.americannational.com/tfs/defaultcollection/_apis/projects?$top=300&api-version=5.0")
{
Authenticator = new RestSharp.Authenticators.NtlmAuthenticator()
};
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var jsonString = response.Content;
var jo = JObject.Parse(jsonString);
//...
}
I am wanting to load the names of the projects into the Array so that I can later iterate through them. Any help is appreciated, I have tried a few things but not having much luck.
you can use var jo = JsonConvert.DeserializeObject<Rootobject>(jsonString);
and then iterate through jo.value
try this
var jsonDeserialized= JsonConvert.DeserializeObject<Rootobject>(json);
as example how to use it this query returns array of project names
var projectNames= jsonDeserialized.value.Select(v => v.name ).ToArray();
output
["IIBTest","MS Project POC","WorkflowReporting","iSolutions","Training"]
this returns a list of projects
var projects= jsonDeserialized.value.ToList();
I am trying to assign the value of a key from an async JSON response to a variable, the JSON key in question is the "threatType" Key. I am querying google's safebrowsing v4 API and I get a good response, the problem is when I try to assign a key to a variable nothing is assigned. Here's my code:
public static async Task<string> CheckUrl( string Api_Key, string MyUrl)
{
safeBrowsing_panel i = new safeBrowsing_panel();
var service = new SafebrowsingService(new BaseClientService.Initializer
{
ApplicationName = "Link-checker",
ApiKey = Api_Key
});
var request = service.ThreatMatches.Find(new FindThreatMatchesRequest()
{
Client = new ClientInfo
{
ClientId = "Link-checker",
ClientVersion = "1.5.2"
},
ThreatInfo = new ThreatInfo()
{
ThreatTypes = new List<string> { "SOCIAL_ENGINEERING", "MALWARE" },
PlatformTypes = new List<string> { "ANY_PLATFORM" },
ThreatEntryTypes = new List<string> { "URL" },
ThreatEntries = new List<ThreatEntry>
{
new ThreatEntry
{
Url = MyUrl
}
}
}
});
var response = await request.ExecuteAsync();
string json = JsonConvert.SerializeObject(await request.ExecuteAsync());
string jsonFormatted = JToken.Parse(json).ToString(Formatting.Indented);
Console.WriteLine(jsonFormatted);
return jsonFormatted;
}
I created classes to parse the json:
public class ThreatRes
{
public string threatType;
}
public class RootObjSB
{
public List<ThreatRes> matches;
}
And I call it with:
string SB_Result = await CheckUrl("MyAPIKey", "Bad_URL");
RootObjSB obj = JsonConvert.DeserializeObject<RootObjSB>(SB_Result);
The JSON response from google:
{
"matches": [
{
"cacheDuration": "300s",
"platformType": "ANY_PLATFORM",
"threat": {
"digest": null,
"hash": null,
"url": "http://badurl.com/",
"ETag": null
},
"threatEntryMetadata": null,
"threatEntryType": "URL",
"threatType": "SOCIAL_ENGINEERING",
"ETag": null
}
],
"ETag": null
}
I need help please.
So I tried using JavaScriptSerializer and it seemed to work just fine, I also reconstructed my classes to parse all the properties on the JSON response.
Reconstructed Classes:
public class Threat
{
public object digest { get; set; }
public object hash { get; set; }
public string url { get; set; }
public object ETag { get; set; }
}
public class Match
{
public string cacheDuration { get; set; }
public string platformType { get; set; }
public Threat threat { get; set; }
public object threatEntryMetadata { get; set; }
public string threatEntryType { get; set; }
public string threatType { get; set; }
public object ETag { get; set; }
}
public class RootObjSB
{
public List<Match> matches { get; set; }
public object ETag { get; set; }
}
and i deserialize it like this:
string SB_Result = await CheckUrl("MyAPIKey", "Bad_URL");
var obj = new JavaScriptSerializer().Deserialize<RootObjSB>(SB_Result);
string threat = obj.matches[0].threatType;
Console.WriteLine(threat);
I really don't know why the first option I tried didn't parse the data correctly but this was how I overcame that problem. Hope it helps anyone going through the same thing
Hey all so here is the JSON string I expect back {\"status\":\"success\",\"locations\":[{\"id\":\"24\",\"name\":\"Test New Location Test\",\"contact_first_name\":\"Test\",\"contact_last_name\":\"Test\",\"contact_email\":\"test#email.com\",\"contact_phone_number\":\"(555) 555-5555\",\"billing_address\":\"Test\",\"billing_city\":\"Test\",\"billing_state\":\"AK\",\"billing_zip\":\"55555\",\"traps\":[]}]}
I am trying to store all the different parts that make up a location to an object list such as id, name, contact_first_name etc.. I think what is tripping me up is the status in front that is making it a little more difficult for me access the different locations.
I am following this tutorial that seems pretty clear but haven't gotten it to work on my end yet. https://www.youtube.com/watch?v=XssLaKDRV4Y
The below code is part of my Service class and it works in getting the expected http response (mentioned above) and getting the success message. When I uncomment the few lines of code below my app breaks and doesn't store any objects to a list.
public async Task<string> GetLocationData()
{
var user_id = Convert.ToString(App.Current.Properties["user_id"]);
var session = Convert.ToString(App.Current.Properties["session"]);
var key = "randomkeystring";
var body = new List<KeyValuePair<string, string>>();
body.Add(new KeyValuePair<string, string>("user_id", user_id));
body.Add(new KeyValuePair<string, string>("session", session));
body.Add(new KeyValuePair<string, string>("key", key));
try
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "apiurl/api/something") { Content = new FormUrlEncodedContent(body) };
var result = await client.SendAsync(request);
if (!result.IsSuccessStatusCode)
{
return "false";
}
//string representation
var stringResponseFromServer = await result.Content.ReadAsStringAsync();
//convert JSON to series of objects
//LocationCollection locationCollection = JsonConvert.DeserializeObject<LocationCollection>(stringResponseFromServer);
//System.Diagnostics.Debug.WriteLine(locationCollection.locations.Count);
var response = JsonConvert
.DeserializeObject<GetLocationDataResponse>(stringResponseFromServer);
if (response == null) return "false";
jsonString.HttpGetLocationDataString += stringResponseFromServer;
return stringResponseFromServer;
}
}
catch
{
return "false";
}
}
My locations.cs looks like this
public class Locations
{
public int id { get; set; }
public string name { get; set; }
public string contact_first_name { get; set; }
public string contact_last_name { get; set; }
public string contact_email { get; set; }
public string contact_phone_number { get; set; }
public string billing_address { get; set; }
public string billing_city { get; set; }
public string billing_state { get; set; }
public string billing_zip { get; set; }
public string traps { get; set; }
}
Then I have a LocationCollection.cs where i hope to store the different locations so I can loop through them later and do whatever I need to do to them.
public class LocationCollection
{
public List<Locations> locations { get; set; }
}
And then I call the method on my MainPage after the user logs in
insectService.GetLocationData().ContinueWith(async (task) =>
{
var getLocationDataResponse = JsonConvert.DeserializeObject<GetLocationDataResponse>(task.Result);
if (getLocationDataResponse.status == "failure")
{
await DisplayAlert("Location Data Failure", "Could not retrieve data", "Try Again");
await Navigation.PushModalAsync(new LoginPage(), true);
}
//System.Diagnostics.Debug.WriteLine(getLocationDataResponse.locations.ToString());
if (getLocationDataResponse.status == "success")
{
await DisplayAlert("Location Data Success", "Successfully Recovered Data", "Back to Main Page");
}
}); //TaskScheduler.FromCurrentSynchronizationContext());
Right now I am able to get the expect JSON string of {\"status\":\"success\",\"locations\":[{\"id\":\"24\",\"name\":\"Test New Location Test\",\"contact_first_name\":\"Test\",\"contact_last_name\":\"Test\",\"contact_email\":\"test#email.com\",\"contact_phone_number\":\"(555) 555-5555\",\"billing_address\":\"Test\",\"billing_city\":\"Test\",\"billing_state\":\"AK\",\"billing_zip\":\"55555\",\"traps\":[]}]} and am able to check if the status is success or failure. However I am having trouble storing the different parts of "locations" into a list. Any suggestions?
You can give a try deserilizing your api result in to a result model, then from there again de serialize to location model. Example:
My API Model
public class ApiResult
{
public Int32 Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
}
Inside Data I copy all my return result from API, then Deserialize to exact Model. Here is the example:
public static List<Models.OrderList> RetrieveOrderList(string host, List<Models.FilterCondition> filter)
{
string sResult = HttpHelper.httpPost(host + "api/Order/RetrieveOrderList", Newtonsoft.Json.JsonConvert.SerializeObject(filter));
Models.ApiResult mResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.ApiResult>(sResult);
if (mResult.Status == 0)
throw new Exception(mResult.Message);
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Models.OrderList>>(mResult.Data);
}
If you see the above My return result(string), I deserialize to API result Model, then again finally deserialize to OrderList Model. Hope this help to sort out your issue.
Update: API Controller
I forgot to mention one more point. On the API Controller Side Your result need to copied to API Model.
Here is the Example
[HttpPost]
public Models.ApiResult RetrieveOrderList(List<Models.FilterCondition> conditions)
{
Models.ApiResult mResult = new Models.ApiResult();
try
{
List<Models.OrderList>mOrderList= BLL.Order.RetrieveOrderList(conditions);
mResult.Status = 1;
mResult.Message = "Success";
mResult.Data = Newtonsoft.Json.JsonConvert.SerializeObject(mOrderList);
return mResult;
}
catch (Exception ex)
{
mResult.Status = 0;
mResult.Message = ex.Message;
mResult.Data = "";
return mResult;
}
}
My locations model didn't match the JSON response. Once I read what the exception was in my catch statement I saw that 'traps' was supposed to be another list. After I changed traps property to a List and then made another class for 'traps' everything worked fine.
I am unable to deserialize my custom object.
public class UserInfo
{
public int Id1 { get; set; }
public string Code { get; set; }
public int Id2 { get; set; }
public List<string> Roles { get; set; }
public string Eg1 { get; set; }
public DateTime Time{ get; set; }
public string Eg2 { get; set; }
public string Version { get; set; }
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<UserInfo>(raw);
The Deserialize is throwing an exception
"Cannot convert object of type 'System.String' to type 'UserInfo'"
JSON Contents:
"\"{\\\"Id1\\\":0,\\\"Code\\\":null,\\\"Id2\\\":0,\\\"Roles\\\":null,\\\"Eg1\\\":\\\"Eg2\\\",\\\"Time\\\":\\\"\\\\/Date(-62135596800000)\\\\/\\\",\\\"Version\\\":\\\"1.0.0.0\\\"}\""
Note: Let me know, if it is unclear. I'll edit the question.
-- edited. ID2 changed to Id2. The real class is different in terms of variable names. Hence the issue.
Your string is a C# string containing a JavaScript string containing JSON. Short of fixing what you're being sent, here's how you would deserialize:
var jsonString = serializer.Deserialize<string>(raw);
return serializer.Deserialize<UserInfo>(jsonString);
You are passing a Javascript string to your deserializer because you have your object within an escaped string.
After unescaping it, this is what the serializer receives:
"{\"Id1\":0,\"Code\":null,\"Id2\":0,\"Roles\":null,\"Eg1\":\"Eg2\",\"Time\":\"\\/Date(-62135596800000)\\/\",\"Version\":\"1.0.0.0\"}"
What you really want to send it is:
{"Id1":0,"Code":null,"Id2":0,"Roles":null,"Eg1":"Eg2","Time":"\/Date(-62135596800000)\/","Version":"1.0.0.0"}"
Your ID2 is all caps in the JSON and the Id2 is not in your class.
EDIT:
Try creating an instance of the object and serialize it to JSON to compare and see if the JSON is correct or not. You can then use that string to properly format.
The code below should help someone get up and running.
the above code will cause an error on because string has no default constructor.
If a string is passed in from JSON.stringify() client JavaScript method the second Deserialize may work if the object passed in maps to the public fields in the object.
Let's look at a quick example presuming an .ASHX file receives the request from a jQuery call that looks like this:
//Called from with a jQuery ready() in a simple html page
var getNewPerson = function ()
{
var NewPerson = new Object();
NewPerson.PersonID = "0";
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
var arrObj;
var str = "";
var webMethod = "http://someserver.com/admin/DataHandler.ashx";
$.ajax({
cache: false,
url: webMethod,
type: "POST",
dataType: "json",
/* for hashtable or .net web service - data: "{\"NewPerson\":" + JSON.stringify(NewPerson) + "}", */
data: JSON.stringify(NewPerson),
contentType: "application/json; charset=utf-8"
}
)
.done( function(){}... code here ...etc)
//Valid JSON object format: {"PersonID":"1","FirstName":"Rick","LastName":"Wright","Address":"4520 No Such address Ave.","City":"Riverside","State":"CA","Zip":"92503"}
//And here is a sample class on the C# side in the .ashx handler page.
public class NewPerson
{
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
} // EOC Person
// And in the process request
public void ProcessRequest(HttpContext context)
{
string jsonString = "";
string rawJson = "";
System.Diagnostics.Debugger.Break();
HttpContext.Current.Request.InputStream.Position = 0;
string responseString;
var jsonSerializer = new JavaScriptSerializer();
/*Set the stream position to 0 */
context.Request.InputStream.Position = 0;
using (System.IO.StreamReader inputStream = new StreamReader(context.Request.InputStream))
{
rawJson = inputStream.ReadToEnd();
}
var objNewPerson = jsonSerializer.Deserialize<NewPerson>(rawJson);
if (clientList != null)
{
responseString = objNewPerson.FirstName + " " + objNewPerson.LastName ;
}
else
resp="No Record Found";
} // eof ProcessRequest