Json serialization in asp.net mvc c# - c#

public ActionResult About()
{
List listStores = new List();
listStores = this.GetResults(“param”);
return Json(listStores, “Stores”, JsonRequestBehavior.AllowGet);
}
Using the above code I am able to get the below result :
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
"email":"abc#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
how would I able to get the result in below format? Would need stores at the beginning of the result.
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
"email":"abc#ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"
}} ] }

Try
return Json(new { stores = listStores }, JsonRequestBehavior.AllowGet);
In the above statement, you're creating a new object with a property named "stores", which is then populated with the array of items from the list.
You could also use a class, something defined like so:
[DataContract]
public class StoreListJsonDTO
{
[DataMember(Name = "stores")]
public List Stores { get; set; }
public StoreListJsonDTO(List storeList)
{
this.Stores = storeList;
}
}
Then in your code, you'd do:
var result = new StoreListJsonDTO(listStores);
return Json(result, JsonRequestBehavior.AllowGet);

Related

Labeling values returned from API

This method returns a bool and a string -
public (bool active, string name) Report()
{
}
From my controller, I call it like this -
public IActionResult Credit([FromBody] Data data)
{
return Ok(Report())
}
The response I get is something like this -
{
"item1": false,
"item2": "Your name"
}
How do I get this response instead -
{
"Active": false,
"Name": "Your name"
}
The quick and easy way would be to return an anonymous type, taking the values from the returned tuple
public IActionResult Credit([FromBody] Data data)
{
//...
var report = Report();
return Ok(new
{
Active = report.active,
Name = report.name
})
}
Ideally you should return a strongly typed model that can be returned from the API
public class ReportModel
{
public string Name { get;set; }
public bool Active { get;set; }
}
and update accordingly
public ReportModel Report()
{
//...
}
public IActionResult Credit([FromBody] Data data)
{
//...
var report = Report();
return Ok(report);
}
Value tuples (as you are using for the return from your Report() method) are just syntactic sugar around a ValueTuple<T,T,...,T> object. Therefore, the real property names are not active and name but, in fact, item1 and item2.
So your method gets converted to something like this:
[return: TupleElementNames(new string[] {
"active",
"name"
})]
public ValueTuple<bool, string> Report()
How do you resolve this? You should create a model that reflects what you want to return:
public class ActiveName
{
public string Name { get;set;}
public bool Active {get;set;}
}
and then change your method to return this ActiveName type.
Another way is to return an anonymous type as dynamic, but I recommend against this approach since using dynamic introduces the potential for runtime errors if mistakes are made. If you're just using it to return from your API method, then it's probably OK.
public dynamic Report()
{
return new { name = "abc", active = true };
}
public IActionResult Credit([FromBody] Data data)
{
var x = Report();
return Ok(new {Active = x.Item1, UserName = x.Item2});
}

How can i see if my JSON contains a certain value and then compare it?

var Name = "Resources.myjson.json";
var NameJSON = new System.IO.StreamReader(typeof(Strings).GetTypeInfo().Assembly.GetManifestResourceStream(Name)).ReadToEnd();
var ParsedBrandJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<TheInfo>(NameJSON);
await JsonCS.LoadJson(ParsedBrandJSON);
And on the page:
static public class TheInfoJSON
{
static public TheInfo Data { get; set; }
static public async Task LoadJson(Data JSON)
{
Data = JSON;
}
}
and
public class TheInfo
{
public List<TheName> TheName { get; set; } = new List<TheName>();
}
My json:
{
"TheInfo":[
{
"TheName": ["Martin", "Jonas", "Alex", "Oscar"]
}
]
}
When i now try to compare how can i see if my JSON contains a certain object and then store that as a single TheName? Is it possible to do it in the same cast?
var TheNameDataFromOtherPage = OtherPage.TheName; //Here i gather the name from another page that i will compare with the JSON
//Wrong syntax
bool DoTheyMatch = TheNameDataFromOtherPage == TheInfoJSON.Data.TheName.Contains("Alex");
This is now wrong syntax because i cant compare the value to a bool. How can i get out the data i find and then instead of having TheInfoJSON.Data.TheName.Contains("Alex"); as a bool, back to a single value of TheName containing "Alex" so I can create a bool out of the two values to see if the JSON has it or not.
I tried to add something along the lines like this after the contains(): as TheInfo.TheName but that isnt the correct syntax either.
bool DoTheyMatch = TheInfoJSON.Data.TheName.Contains(TheNameDataFromOtherPage);

How to create response from dictionary?

I am trying to create below response from dictionary:
['Employee1'] : List of skills
Code :
public class Skills
{
public string Skill {get;set;}
}
var skills=FetchSkills();
var dictionary = new Dictionary<string, List<Skills>>();
dictionary.Add('Employee1',skills);
Now i am trying to create below response:
'Employee1' =
{
{"skill":"skill1"},{"skill":"skill2"},{"skill":"skill3"}
}
I want skill property in camel case in my final response.
This is how i am trying to create response but not getting how to create expected response:
return Json(dictionary.Select
(
), JsonRequestBehavior.AllowGet);
Given class
public class Skills {
[JsonProperty("skill")]
public string Skill {get;set;}
}
and used like this
var skills=FetchSkills();
var dictionary = new Dictionary<string, List<Skills>>();
dictionary.Add('Employee1',skills);
return Json(dictionary, JsonRequestBehavior.AllowGet);
should produce
{
"Employee1":[
{"skill":"skill1"},{"skill":"skill2"},{"skill":"skill3"}
]
}

Using JArray for serializing data from database in WebAPI (C#)

I want to achieve the following JSON data:
[
{
"name":"Deutschland",
"code":"de"
},
{
"name":"Frankreich",
"code":"fr"
},
{
"name":"Japan",
"code":"jpn"
}
]
Currently I'm getting this result of JSON data:
{
"groups":[
{
"name":"Deutschland",
"code":"de"
},
{
"name":"Frankreich",
"code":"fr"
},
{
"name":"Japan",
"code":"jpn"
}
]
}
Here is the code of the Controller:
public dynamic GetGroups()
{
JObject o = JObject.FromObject(new
{
groups = from g in db.QR_Groups
select new
{
name = g.name,
code = g.code
}
});
return o;
/*Here I've tried to get JSON data as array without the Property "groups"*/
//JArray a = new JArray(
// from g in db.QR_Groups
// select new JValue(g));
//return a;
}
Can anyone tell me how to retrieve the JSON data as per the first JSON example above?
And is the type "dynamic" good practice for the method?
First of all there is no need to do serialization manually. ASP.Net WebApi MediaFormatters are going to take care of it based on the Request Content-Type. So Create a class as shown below.
public class Group
{
public string name { get; set; }
public string code { get; set; }
}
Then your Web API endpoint should be -
[HttpGet]
public HttpResponseMessage GetCountries()
{
List<Group> groups = (from g in db.QR_Groups
select new Group
{
name = g.name,
code = g.code
}).ToList();
return Request.CreateResponse(HttpStatusCode.OK, groups);
}
And when I make a Fiddler request, I was able to get the output which you are interested -
Try this one:
var json = JsonConvert.SerializeObject(from g in db.QR_Groups
select new
{
name = g.name,
code = g.code
});
And is the type "dynamic" good practice for the method?
no, it's not best practise. Better one is to create new class

How to return data in object format for web api?

I have to return data in json format but it says cannot implicitly convert type string to system.collection.generic.list(object).
[HttpGet]
public List<object> GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
// return myCo----------> works
string json = JsonConvert.SerializeObject(myCo);
return json; ------- > not works conversion error & i need this
}
I tried tostring() and many other ways but nothing worked. How can I convert string to object?
Here is my function code AllDefCompany2
public static List<object> AllDefCompany2
{
get
{
using (var db = new RPDBEntities())
{
return db.DefCompanies.Select(b => new
{
Id = b.Id,
CurrentCurrencyCode = b.CurrentCurrencyCode,
ShortName = b.ShortName,
FullName = b.FullName,
ContactPerson = b.ContactPerson,
Address1 = b.Address1,
CompanyCity = b.CompanyCity,
CompanyState = b.CompanyState,
CompanyCountry = b.CompanyCountry,
ZipPostCode = b.ZipPostCode,
TelArea = b.TelArea
}).ToList<object>();
}
}
}
this code helps me to solve both api and kendo problem
[HttpGet]
public List<object> GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
object json = JsonConvert.SerializeObject(myCo);
return json;
}
here is configuration settings
using System.Data.Entity;
namespace RpManticSolAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
}
}
return JsonConvert.SerializeObject(myCo);
You can convert string to object, but what you are trying to do in the code shown is convert it to a List<object>. You can try calling AsEnumerable or ToList on the json variable.
But if what you want to do is return a string, why not change the return type of the method?
[HttpGet]
public string GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
// return myCo----------> works
string json = JsonConvert.SerializeObject(myCo);
return json; ------- > not works conversion error & i need this
}
Try this. Need to change function return type based on whether you return list of objects or string (in this case json)

Categories