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.
Related
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.
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.
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
The serialization of the array returns the following JSON:
[{"Code":"AAAA","Description":"Description of AAAA"},{"Code":"BBBB","Description":"Description of BBBB"}]
My goal is to return the following JSON:
{"AAAA":{"Description":"Description of AAAA"},"BBBB":{"Description":"Description of BBBB"}}
You can achieve something simliar (not exactly the same you are expecting) if instead of serializing an array, build a temporary Dictionary and serialize it.
var dict = new Dictionary<String, YourClass>();
foreach (YourClass yourObj in listOfObjs)
{
dict[yourObj.Code] = yourObj;
}
// then serialize "dict"
You could add a rule to your JSON serializer to make it avoid serializing "code" property in YourClass, and you will end up with a JSON object exactly as you show in your example.
You'll need to either use a class that has the "AAAA" and "BBBB" properties, or you'll need to serialize a dictionary instead. As it is, you're serializing an array and getting an array.
The table on this blog post shows several search starting points.
.Net has built-in System.Web.Script.Serialization.JavaScriptSerializer, here, with examples
The .Net one doesn't specially serialize Dictionary the way you want, but some of the others do, I believe. However, I think there are reasons NOT to want a general serialization routine the way you've requested - though I can't list them certainly.
I need to serialize the strings from a resource file (.resx) into a JSON object. The resource file's keys are in flux and thus I cannot just create a C# object that accepts the appropriate values. It needs to be a dynamic solution. I am able to loop through the key-value pairs for the file, but I need an easy way to serialize them to JSON.
I know I could do:
Object thing = new {stringOne = StringResource.stringOne; ...}
But, I'd rather have something like:
Object generic = {}
foreach (DictionaryEntry entry in StringResource) {
generic.(entry.Key) = entry.Value
}
Or should I just create a custom JSON serializer that constructs the object piecemeal (i.e. foreach loop that appends part of the JSON string with each cycle)?
EDIT
I ended up writing a quick JSON serializer that constructs the string one field at a time. I didn't want to include a whole JSON library as this is the only use of JSON objects (for now at least). Ultimately, what I wanted is probably impractical and doesn't exist as it's function is better served by other data structures. Thanks for all the answers though!
If you're using C# 4.0, you should look at the magical System.Dynamic.ExpandoObject. It's an object that allows you to dynamically add and remove properties at runtime, using the new DLR in .NET 4.0. Here is a good example use for the ExpandoObject.
Once you have your fully populated ExpandoObject, you can probably easily serialize that with any of the JSON libraries mentioned by the other excellent answers.
This sounds like an accident waiting to happen (i.e. creating output prior to cementing the structure), but it happens.
The custom JSON serializer is a compelling option, as it allows you to easily move from your dictionary into a JSON format. I would look at open source libraries (JSON.NET, etc) to see if you can reduce the development time.
I also think setting up in a slightly more structured format, like XML, is a decent choice. It is quite easy to serialize from XML to JSON using existing libraries, so you avoid heavy customization/
The bigger question is what purposes will the data ultimately serve. If you solve this problem using either of these methods, are you creating bigger problems in the future.
Probably I would use JSON.NET and the ability to create JSON from XML.
Then, you could create an XML in-memory and let JSON.NET convert it to JSON for you. Maybe if you dig deeper into the API, there are other options, too.
Newtonsoft is a library that has all kinds of nifty JSON tools...among them, on-the-fly one-line serializer and deserializers...check it out, it's my favorite JSON library out there
http://james.newtonking.com/pages/json-net.aspx
If I remember correctly, it has a class that will convert JSON to a .NET object without having to create the .NET object first. Think it is in the Json.Convert class
The way I do it is:
var serialiser = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serialiser.Serialize(data);
context.Response.Write(json);