ASP.NET WEB API: Why I dont have complete Json? - c#

My Problem is that when I browse to the service URL I see "key-value" pairs but I don't see the name of the array or object, I need the name because I want to use that service for android.
it looks like this:
My code looks like this:
1. In ValueController I have method:
[AcceptVerbs("GET", "POST")]
public List<BuzzMonitor.Web.Message> Search(string text, DateTime dateFrom, DateTime dateTo, [ModelBinder]List<int> themeIds, [ModelBinder]List<int> sourceIds)
{
MessageHandler mh = new MessageHandler();
List<BuzzMonitor.Web.Message> messages = null;
messages = mh.Search(text,dateFrom,dateTo,themeIds,sourceIds);
return messages;
}
2. In Global.asax I added:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Does anyone have an idea on what is missing when I don't see full JSON, and see just key:value pairs? Thank you for help!

I think you are thinking that you are not seeing the array name or class right? and that is an error?
The answer is NO.
Reason? Well, JSON was invented to share objects easily over network and the main goal was to make it independent of the underlying architecture -
http://www.json.org/
that is why you don't see array names or variable names, only the object notation. Thats JSON stands for Java Script Object Notation. It's the responsibility of the receiving side to re-construct the object from the data provided in json format.
in your case messages is an array with a list of data and so does the output -
[] means array and {} inside that means it has only one object in it.
EDIT: You can also use this to parse json -
http://developer.android.com/reference/org/json/JSONTokener.html

Related

Tuple Serialize in ApiController - C#

I'm using ApiController and I want it to return a list of tuples, like: List<Tuple<DateTime,DateTime>>.
(My action returns it in IHttpActionResult object.)
The problem is, when I receive the response and I try to deserialize it to the above object - list of tuples, I got a strange result the json in my client side is: [{"m_Item1":"2020-01-30T12:13:23","m_Item2":"2020-01-30T12:13:23"}].
I want it to look like this: [{"Item1":"2020-01-30T12:13:23","Item2":"2020-01-30T12:13:23"}].
Maybe somebody knows how can I avoid it?
I know that I can create an object which contains 2 fields of datetimes, but I don't want because my client does not know the server, so it also doesn't know the object that I declare...
Or maybe you have another idea to resolve it?
Thanks a lot!
Yeah, it's extremely easy to avoid this issue. Create a proper dto class like every good person should and return it from your api instead.

Returning JSON string from 3rd party API in ASP.Net MVC controller

I'm wrapping a third-party API in a controller (due to security hoops we have to jump through) and the API returns a JSON string.
I do some minor changes to the JSON string and want to return that string.
I don't see a way to do that with a JSONResult, as it requires an object, and returning JSON string is sent back as a string.
Am I stuck with using something like a ContentResult?
JSONLint.com says the modified JSON is valid. It starts with...
[{"Acknowledgment Start Date":null,"Additional Location Details":null,"Area Code":null,"Assign To Vendor":"No",...
If I use the Newtonsoft.Json.JsonConvert(), it does this to my JSON string...
[[[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],...
If I use JavaScriptSerializer, I get this again...
[[[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],...
I suspect part of the problem is the null values in the JSON string.
Is there another solution? Are there issues with using a ContentResult that I'm not aware of?
Newtonsoft.Json.JsonConvert() serializes an object, it doesn't parse (AKA deserialize) it. What you're doing when you call Newtonsoft.Json.JsonConvert(jsonString) is you're saying "serialize this JSON string to JSON". So, you get a funky result.
You could instead parse the JSON, then make your modifications, then serialize it again. For example:
var myObject = Newtonsoft.Json.DeserializeObject<POCOClass>(jsonString);
myObject.Whatever = "123";
//... etc.
This of course after defining your POCO class like such:
public class POCOClass {
[JsonProperty(PropertyName = "Acknowledgment Start Date")]
public string AcknowledgmentStartDate { get; set; }
// etc.
}
Then when you're done, serialize it back:
jsonString = Newtonsoft.Json.JsonConvert(myObject) // or Newtonsoft.Json.SerializeObject(myObject)
Upon closer inspection, I had a couple of realizations.
The first being that the outputted JSON isn't valid because the quoted identifiers include spaces and colons. For example, this one from above.
... ,"Additional Location Details":null, ...
While I suspect this is the root of problems, I don't have the time to write a parser to make it proper JSON.
I will come back and write a tool to properly clean up the mess at some point, but right now I have another approach I'm doing.

Dummy Objects Good or Bad

I am working on a project that communicates a lot of data with a server. This data is in a json format. We end up creating a lot of dummy objects to parse the json data. This leads to having a lot of classes that just contain class members. Is there a better way of doing things?
thanks
Assuming that you are using NewtonSoft's JSON parser or something similar, you have a couple of choices here. The usual use case here is to deserialize to a named type, thus:
var parsedMessage = JsonConvert.DeserializeObject<Message>(content.AsString());
If you have many types for each differnet JSON message type you wish to receive and wish to avoid to, you can do the following:
var parsedMessage = JsonConvert.DeserializeObject<dynamic>(content.AsString());
This will give you a dynamic object that you can inspect and should also work given other Json libraries. Alternatively, NetwtonSoft also provides the following method:
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject);
This will allow you to deserialize to an anonymously typed object rather than a dynamic object.

Deserialize simple string array

I have a simple HTTPHandler pretending to be a Web Service
(platform constraints, don't judge me)
I want to be able to create a string array in javascript, stringify it, and send it in a REQUEST header to be consumed as a set of parameters.
My issue is, most of the deserialization methods require you to create a named object and deserialize the whole object. I just want the simple string, man.
var ar = [];
ar.push("one");
ar.push("two");
var arStr = JSON.stringify(ar);
//$Ajax() bla bla bla
//sends out as "[\"one\",\"two\"]"
I'm sure there is a simple answer, but so far I can't find it.
Addition
Platform constraints also limit me from using 3rd part libraries. Needs to be straight .NET
Your json is a string array/List. All you need is (using Json.Net)
List<string> list = JsonConvert.DeserializeObject<List<string>>(jsonstring);
If you are using JavaScriptSerializer
var list = new JavaScriptSerializer().Deserialize<List<string>>(jsonstring);
BTW: if you are using ajax, you don't need to stringify the object. Just post it as object. The library internally handles it, otherwise you may need double-deserialiazation at receiver end.
String.join(",", ar) if you can make sure that your strings don't contain the separator character.

ServiceStack and JSV: When I serialize a Dictionary<string, object> the type of 'object' is lost on deserialization

In a POCO object, that I persiste using OrmLite, I have the following property:
....
public Dictionary<string, object> CustomData { get; set; }
...
This property is filled with data, like:
customData.Add("_GooglePassword", "blabla"); // this is a String
customData.Add("_ServerPort", 8093); // this is an Int32
// etc...
It is saved in the database as JSV, like this:
{_GooglePassword:blabla,_ServerPort:8093}
The problem comes when I deserialize this, back to the Dictionary in C#, then it puts everything back as strings, as this exception in VS shows:
So, instead of getting it back to an Int32 as it is defined in the class, I get strings, which will give be problems. Im pretty sure that using normal JSON and the DataContract-approach would not have this issue, as I use JSON in other parts.
Am I missing something here?
Thanks =)
Some interesting viewpoints of why inheritance in DTOs is a bad idea from ss author and here.
If your settings can be splitted in profiles, I would suggest you to split in interfaces /classes each cluster of properties and store them in separated strongly-typed properties.
Depending on your context, if you are just storing information and you are not processing or applying business rules to those settings you might receive the dynamic json in a property and storing it as a string. This way you don't create a Settings class just for storing purpose.

Categories