Json data serialized with JsonConvert.SerializeObject is always string in ASP.NET Web API - json

I am developing a ASP.NET MVC Web Api. Project. I am returning data with JSON format. Before I return data to user I serialize data using JsonConvert.SerializeObject to change their json property names.My code return data in JSON format. But with an issue. That is it always return data into string even if the data is array or object.
This is my action method that returns json.
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions!=null && dbRegions.Count()>0)
{
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
if(!string.IsNullOrEmpty(json))
{
json = json.Trim(new char[] { '"' });
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent(json.GetType(),json,Configuration.Formatters.JsonFormatter)
};
}
Actually this code should return Json array. But when I parse data from client (from Android using Volley). It cannot be parsed into Json Array.
This is the data I get:
As you can see the double quote both in the beginning and at the end. The reason I cannot parse it into array in Volley is it is returning as a string because of that double. How can I serialize it trimming that quote? I used trim, but not removed.

You are unnecessarily complicating things. In Web API you can return JSON just by returning any object inside the built-in methods, the framework will serialize it for you.
public IHttpActionResult Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions != null && dbRegions.Count() > 0) {
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
return Ok(regions);
}
As an aside: from what I can see you are mapping manually your domain objects into DTOs: take into consideration the use of an automatic mapping mechanism like AutoMapper.

I am not sure this is the best solution or not. I solved the problem using this way.
This is my action method
public HttpResponseMessage Get()
{
try
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.Default, "application/json")
};
}
catch
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}

It's not required to convert object to json string.
You can try :
return Request.CreateResponse<List<ContentRegion>>(HttpStatusCode.OK,regions);
Not tested.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Use this line in your WebApiConfig.
And here your code should be
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
HttpResponseMessage temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "");
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, regions);
return temp;
//string json = JsonConvert.SerializeObject(regions);
//if (!string.IsNullOrEmpty(json))
//{
// json = json.Trim(new char[] { '"' });
//}
//return new HttpResponseMessage(HttpStatusCode.OK)
//{
// Content = new ObjectContent(json.GetType(), json, Configuration.Formatters.JsonFormatter)
//};
}

Related

System.Collections.Generic.List`1[System.String]" JSON error

I'm trying to use JSON and I was use PostMan to return Response
this error happent
System.Collections.Generic.List`1[System.String]"}
public ActionResult SendVFCode(string Phone_Number)
{
var jsonSerialiser = new JavaScriptSerializer();
string error = "";
var SearchData ="";
if (Phone_Number == null)
{
error = "Must enter your phone number";
}
else if ( (db.PhoneNumbers.Select(x =>x.Id).Count() < 0)
&& (db.Assistant.Select(x =>x.Id).Count()) < 0)
{
error = "There are no data or your account is not activated";
}
else
{
SearchData = db.PhoneNumbers.Include(x => x.Assistant)
.Where(x => x.PhoneNumber == Phone_Number
&& x.Assistant.IsActive == true).Select(xx =>xx.PhoneNumber).ToList().ToString();
}
json = new
{
err = error,
ResultSearchData = SearchData
};
return Content(jsonSerialiser.Serialize(json));
}
SearchData is not a string. Don't declare it as string and don't try to shove a string into it. It's a List (probably of type List<string> or whatever your Phonenumber type is).
var SearchData =""
Should be:
List<string> SearchData;
And your database call should end in .ToList(), not .ToList().ToString().
Note that ToList() followed with ToString() returns fully-qualified name of the list instead of the list contents, hence you should use List<string> to hold result strings (also the list must be instantiated first before used inside if-block). The correct setup should be like this:
public ActionResult SendVFCode(string Phone_Number)
{
var jsonSerialiser = new JavaScriptSerializer();
string error = "";
var SearchData = new List<string>(); // instantiate list of strings
var phoneCount = db.PhoneNumbers.Select(x => x.Id).Count();
var assistantCount = db.Assistant.Select(x => x.Id).Count();
if (Phone_Number == null)
{
error = "Must enter your phone number";
}
else if (phoneCount < 0 && assistantCount < 0)
{
error = "There are no data or your account is not activated";
}
else
{
// assign list from query results
SearchData = db.PhoneNumbers.Include(x => x.Assistant)
.Where(x => x.PhoneNumber == Phone_Number && x.Assistant.IsActive == true)
.Select(xx => xx.PhoneNumber).ToList();
}
var json = new
{
err = error,
ResultSearchData = SearchData
};
return Content(jsonSerialiser.Serialize(json));
}

JsonResult is sending Json parsed object as empty array collection to browser [[]],[[]]

I'm trying to add to the JsonResult object a parsed Json string, but I couldn't do it, the parser object in the browser is shown as:
"filter":[[[]],[[[],[]]]]
This is the full code
public JsonResult AjaxStandardGet(int id)
{
Standard ec = db.Standard.FirstOrDefault(s => s.IdStandard == id);
// inside filter: { "KeyDynamic1": "Value1", "KeyDynamic2": [ "AAA", "DDD"] }
var filter = JsonConvert.DeserializeObject(ec.Filter);
return Json(new
{
ec.IdStandard,
ec.Description,
filter,
ec.Observations,
Services = ec.StandardServices.Select(s => new {
s.IdStandardServices,
Tecnology = s.Tecnology?.Nombre,
ServiceType = s.ServiceType?.Description,
s.Quantity,
s.Cost,
Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
Total = s.Quantity * s.Cost
}),
Success = true
});
}
I can't create the model object because the filters are not allways the same.
I tried this:
Dictionary<string, object> filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(ec.Filter);
And I get
"filter":{"KeyDynamic1":"Value1","KeyDynamic2":[[],[]]}
I suggest you to JToken or dynamic:
JToken filter = JToken.Parse(ec.Filter);
dynamic filter = JsonConvert.DeserializeObject<dynamic>(ec.Filter);
Here is working fiddle.
Update
It seems that JavaScriptSerializer is not able to do it. So you can serialize your result using Newtonsoft.Json and return it as a string:
var result = new
{
ec.IdStandard,
ec.Description,
filter,
ec.Observations,
Services = ec.StandardServices.Select(s => new {
s.IdStandardServices,
Tecnology = s.Tecnology?.Nombre,
ServiceType = s.ServiceType?.Description,
s.Quantity,
s.Cost,
Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
Total = s.Quantity * s.Cost
}),
Success = true
};
var json = JsonConvert.SerializeObject(result);
return Content(json, "application/json");

How do i send additional object to client.PostAsync (along with file contents)

I have the following MVC post.
It post file contents to API.
[HttpPost]
public ActionResult FileUpload_Post()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1]; file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(requestUri, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.Created)
{
ViewBag.Message= "Created";
}
else
{
ViewBag.Message= "Failed";
}
}
}
}
return View();
}
What if i want to pass additional custom object (preferably json format) along with file contents?
CustomObject obj = new CustomObject;
obj.FirstName = "A";
object.LastName = "B";
Note: Following is Api method that will receive above request.
[HttpPost]
public HttpResponseMessage Upload()
{
if(!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
....
// save the file
....
return new HttpResponseMessage(HttpStatusCode.Created);
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
First you need to serialize the CustomObject into json. e.g. using Json.NET
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
Then you could add the jsonString to the MultipartFormDataContent like:
var jsonContent = new StringContent(jsonString);
content.Add(jsonContent, "CustomObject");
In the Upload API method, get the posted json content by
var jsonString = System.Web.HttpContext.Current.Request.Form["CustomObject"];
If the API project has a reference to class CustomObject, you could deserialize the jsonString with:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomObject>(jsonString);
If not, you could also deserialize it to a dynamic object:
var obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString);

JSON is not working

I have one dropdown in the table.Once I make Onchange event I got all the table value and I want to convert it into json to send it to the servlet.
var item = [];
function dropDownOnChange(e) {
var selectedValue = e.options[e.selectedIndex].value;
alert("selectedValue:" + selectedValue);
var currentRow= $(e).closest("tr");
var AccountNo = $("td:eq(0)",$(currentRow)).text();
alert("accountno"+AccountNo);
var AccountType =$("td:eq(1)",$(currentRow)).text();
alert("acctyp"+AccountType);
var AcctypID = $("td:eq(3)",$(currentRow)).text();
alert("accID"+AcctypID);
Here I tried to convert it to JSON. I want to send this JSON value on my final save.
var objddlvalue = {};
objddlvalue["AccountNo"] = AccountNo;
objddlvalue["AccountType"] = AccountType;
objddlvalue["Account Type_Val"] = AcctypID;
objddlvalue["AccountStatus"] = selectedValue;
item.push(objddlvalue);
console.log(item);
jsonObj1 = JSON.stringify(item);
console.log(jsonObj1);
I am getting my JSON value like:
[{
"AccountNo": "89348734",
"AccountType": "Credit",
"Account Type_Val": "21",
"AccountStatus": "Invalid"
}]
When I check on online JSON checker it says the format is correct. But when I access it form servlet I can not parse it to jarray.
JSONObject jsonObj1 = (JSONObject)JSONValue.parse(request.getParameter("jsondata1"));
System.out.println("Json Object........"+jsonObj1.toJSONString());
JSONArray arr = (JSONArray) jsonObj.get(jsonObj1);
How to loop through my JSON object?
public static void main(String[] args) {
String jsonExternal = "[" +
"{"+
"\"AccountNo\": \"89348734\","+
"\"AccountType\": \"Credit\","+
"\"Account Type_Val\": \"21\","+
"\"AccountStatus\": \"Invalid\""+
"},"+
"{"+
"\"AccountNo\": \"89348734_test\","+
"\"AccountType\": \"Credit_test\","+
"\"Account Type_Val\": \"21_test\","+
"\"AccountStatus\": \"Invalid_test\""+
"}]";
JSONArray arr = (JSONArray)JSONValue.parse(jsonExternal);
for(Object obj : arr) {
JSONObject jsonObj = (JSONObject)obj;
Collection keySet = jsonObj.keySet();
Collection entrySet = jsonObj.entrySet();
Collection values = jsonObj.values();
for(Object o : keySet) {
System.out.println(o.toString());
}
for(Object o : entrySet) {
System.out.println(o.toString());
}
for(Object o : values) {
System.out.println(o.toString());
}
System.out.println(jsonObj.get("AccountNo"));
System.out.println(jsonObj.get("AccountType"));
System.out.println(jsonObj.get("Account Type_Val"));
System.out.println(jsonObj.get("AccountStatus"));
}
}

APEX, Unit Test, Callout No Response with Static Resource

Bit stuck on another one i'm afraid, i am trying to write a unit test for a bulk APEX class.
The class has a calllout to the google api, so i have created a static resource which i am feeding in via a mock, so i can complete testing of processing the JSON that is returned. However for some reason the response is always empty.
Now the very odd thing is that if i use exactly the same callout/JSON code, and the same mock code on a previous #future call, then it does return fine.
Here is the class:
global class mileage_bulk implements Database.Batchable<sObject>,
Database.AllowsCallouts
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c,Shipping_Postcode_2__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';
return Database.getQueryLocator(query);
//system.debug('Executing'+query);
}
global void execute(Database.BatchableContext BC, List<Opportunity> scope)
{
system.debug(scope);
for(Opportunity a : scope)
{
String startPostcode = null;
startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');
String endPostcode = null;
String endPostcodeEncoded = null;
if (a.R2_Shipping_Post_Code__c != null){
endPostcode = a.R2_Shipping_Post_Code__c;
Pattern nonWordChar = Pattern.compile('[^\\w]');
endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');
endPostcodeEncoded = EncodingUtil.urlEncode(endPostcode, 'UTF-8');
}
Double totalDistanceMeter = null;
Integer totalDistanceMile = null;
String responseBody = null;
Boolean firstRecord = false;
String ukPrefix = 'UKH';
if (a.R2_Job_Ref__c != null){
if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){
system.debug('Is Hemel Job');
startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');
} else {
system.debug('Is Bromsgrove Job');
startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');
}
}
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');
req.setMethod('GET');
req.setTimeout(60000);
system.debug('request follows');
system.debug(req);
try{
// callout
HttpResponse res = h.send(req);
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
responseBody = res.getBody();
system.debug(responseBody);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'distance')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
//system.debug(parser.nextToken());
//system.debug(txt);
if (firstRecord == false){
//if (txt == 'text'){
//totalDistanceMile = parser.getText();
system.debug(parser.getText());
//}
if (txt == 'value'){
totalDistanceMeter = parser.getDoubleValue();
double inches = totalDistanceMeter*39.3701;
totalDistanceMile = (integer)inches/63360;
system.debug(parser.getText());
firstRecord = true;
}
}
}
}
}
} catch (Exception e) {
}
//system.debug(accountId);
system.debug(a);
system.debug(endPostcodeEncoded);
system.debug(totalDistanceMeter);
system.debug(totalDistanceMile);
// update coordinates if we get back
if (totalDistanceMile != null){
system.debug('Entering Function to Update Object');
a.DistanceM__c = totalDistanceMile;
a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;
//update a;
}
}
update scope;
}
global void finish(Database.BatchableContext BC)
{
}
}
and here is the test class;
#isTest
private class mileage_bulk_tests{
static testMethod void myUnitTest() {
Opportunity opp1 = new Opportunity(name = 'Google Test Opportunity',R2_Job_Ref__c = 'UKH12345',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());
insert opp1;
Opportunity opp2 = new Opportunity(name = 'Google Test Opportunity 2',StageName = 'qualified',CloseDate = Date.today());
insert opp2;
Opportunity opp3 = new Opportunity(name = 'Google Test Opportunity 3',R2_Job_Ref__c = 'UKB56789',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());
insert opp3;
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('googleMapsJSON');
mock.setStatusCode(200); // Or other appropriate HTTP status code
mock.setHeader('Content-Type', 'application/json'); // Or other appropriate MIME type like application/xml
//Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mock);
system.debug(opp1);
system.debug(opp1.id);
//Call the method that performs the callout
Test.startTest();
mileage_bulk b = new mileage_bulk();
database.executeBatch((b), 10);
Test.stopTest();
}
}
Help greatly appreciated!
Thanks
Gareth
Not certain what 'googleMapsJSON' looks like, perhaps you could post for us.
Assuming your mock resource is well formatted, make sure the file extension is ".json" and was saved with UTF-8 encoding.
If #2 does not work, you should try saving your resource as .txt - I've run in to this before where it needed a plain text resource but expected application/json content type
Be certain that the resource name string you are providing has the same casing as the name of the resource. It is case sensitive.
Are you developing on a namespaced package environment? Try adding the namespace to the resource name if so.
Otherwise, your code looks pretty good at first glance.