So I have a small asp.net app which returns Json objects that are serialized from C# objects. If I just create a function:
[HttpGet(getTheObj)]
public SomeObj GetTheObject()
{
return new SomeObj() { SomeProperty = 1 };
}
Then it works fine and I can do an HttpRequest for the Json object. However I also want to save some these serialized objects into a database for later use. So I'm wondering, can I explicitly call the Json serializer? I understand that several different serializers can be used with ASP.NET, how do I figure out which one I am using (I didn't create the project).
string json = JsonConvert.SerializeObject(_data.ToArray());
you can save this in database. you can again retrive this object from database and deserialize this object.
Related
Here's my situation: I have an MVC3 app that has some very complex C# objects, and those get rendered to a views in this application. However, I have a new requirement: a console application (that I am also writing) will run under a scheduler, and it needs to pull these objects from this MVC3 app, and then do something else with these complex objects.
Since I have control over both apps, I can share a library of the complex objects between them. All of these objects are marked [Serializable]. However, I cannot figure out an easy way to serialize these objects and send them from the MVC3 app to the Console app.
I tried simple JavaScriptSerializer and using the HttpClient to read the string, then deserialize it on the console-app end of things, but unfortunately it doesn't deserialize the data correctly. Everything is null. I can inspect the string on a breakpoint when it arrives at the console app, and all the data is there, in the string, but it just doesn't get de-serialized correctly.
Is there an easier way to do this? I don't care what the serialization method is. The data doesn't have to be passed as JSON and no other application but mine is going to consume these objects. But so far I can't figure out the easiest way to produce/consume these objects.
I know I can go down the whole "create a web service contract" and use data annotations route, but I was hoping there was an easier, less time-consuming way of doing it.
Using Json.NET:
Server-Side
string serializedObject = JsonConvert.SerializeObject(yourComplexObject);
// Send the string to the client...
Client-Side
In the client, you don't even have to know the deserialized object's type, you can take advantage of anonymous objects and dynamic:
string serializedObject = // ... Fetch from server
dynamic complexObject = JsonConvert.DeserializeObject(serializedObject);
// ...
string id = complexObject.UserId;
P.S.: Please note that the object's methods or state is not going to get serialized, only the public properties are.
Can your action just return your object? If so, your client code would look something like (using HttpClient)
var result = client.GetAsync(url).Result;
var myObj = await result.Content.ReadAsAsync<T>();
I need help mapping a complex C# object to a table dynamically, without manually defining a model. I'm using ASP.NET 4.5.
So I am using JSON.NET to serialize my complex C# object into a JSON object with
string json = JsonConvert.SerializeObject(myObject, Formatting.Indented);
This object is being read in dynamically from an external API. It includes complex attributes, like dictionaries, as well as standard strings, integers, etc. I input in a key and it returns the C# object.
I can't manually map the object to a model, since the object does change frequently with development, and needs to be extensible despite changes in the C# object. What is the best way to map this JSON object to a table? Essentially need to be able to render the JSON serialized from the object into a readable table with ASP.NET.
Thanks so much!
I'm calling an API to fetch a list of devices. In my model i have an attribute for list of devices:
public List<Device> device { get; set; }
But, if the API returns 1 device, it's returned as just a Device, not a list of devices with 1 device.
Is there any good way to have a dynamic deserialize? I don't want to have two different models, and parse the JSON programatically just to know which object to deserialize as.
JsonConvert.DeserializeObject<ListDevicesByLabelModel>(responseText);
The dynamic keyword is still great for deserializing JSON, I would recommend that you take a look on this question.
Deserialize JSON into C# dynamic object?
dynamic data = Json.Decode(responseText);
And then you've got a dynamic object to work with instead of needing 2 models.
Otherwise you could also have just one item in the List.
I want to build a service that will pass the data read from the database to the client in JSON format. I don't know the schema table and the types.
I thought about implementing the WCF over Dictionary but the JSON is very complicated and contains objects like "key = ...; value = ..." and i want just "key=value" and i need to return list of Dictionary objects. Sometimes from database i will receive a comma separated array, so i will insert in my Dictionary a key with a new Dictionary as value.
In PHP my boss said that it can be done through associative arrays. Please help me with some ideas or link because i don't know where to start to look.
If there is something that you didn't understood please comment and i will try another explanation.
Edits:
I need it to be a rest service, so JSON is mandatory.
How can i load data from the table ? What type can i use ?
Edit #2 : This is what i want to get : CorectJSON
Edit #3 : This is my current json :
stdClass Object
(
[areaGetStreetTypesResult] => stdClass Object
(
[responseMessage] => [{"name":"IMPASSE","street_type":"IMP"}{"name":"LOTISSEMENT","street_type":"LOT"}{"name":"ROUTE","street_type":"RTE"}{"name":"RUE","street_type":"RUE"}]
[response_status] => stdClass Object
(
[message] => Success : JSON created into the responseMessage variable !
[status] => 0
)
)
)
Is not containing some commas between so it cannot be decoded by php. What should i do ?
This is my method Code
I think that doing everything as a dictionary in webservice API is bad practice and I hate when I need to work with API's like this. If it is a WCF, it produces WSDL and WDSL describes the data is going in and out, so if everything is dictionary, WSDL can not provide anything meaningfull, so your datacontracts tell you nothing about the data.
If you need simply forward database data through webservice, WCF has DataServices http://msdn.microsoft.com/en-us/data/bb931106 although I think you should create API that fits your business needs and is not simple proxy between database and your client.
What is the reason why you need to pass JSON? If you want to create a WCF REST service, it is sufficient to tell WCF to create JSON messages as described here: http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON
If you access the service from a C# application, you don't need to care about how data is passed back and forth. Just take "normal" method parameters and use return values like you'd do locally and you're set.
Example:
string[] GetResultStrings(List<Rectangle> sourceRectangles);
If you really need to pass JSON strings, just pass strings and use the JSON serializer and deserializer to encode the reply and decode the parameters.
For example:
string GetJSONString(string jsonRequest);
The following information may help on using the JSON serializer and deserializer: http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
EDIT
I'm using the following method to serialize serializable objects to JSON:
public static string SerializeJSON(this object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
This works just fine for any DataContract class like:
[DataContract]
public class MyJSONReturnableClass
{
[DataMember]
public string ThisBecomesANamedString;
[DataMember]
public MyJSONReturnableClass[] AndWorksAlsoForNestedArrays;
}
Populate your dictionary, then serialize it using JSon.
Pass it to your client using WCF or RabbitMq...
JsonConvert.SerializeObject(yourDict);
Download the NewtonSoft.dll
Put using:
using Newtonsoft.Json;
I have an ASP.NET web form that is using JQuery on the client-side. I have a user interface that is building a collection of objects and storing them in JSON. With my client-side implementation complete, I need to now work with that information when the user clicks a button. When this button is clicked, I need to loop through that JSON collection and validate the entries. My problem is, I'm not sure how to do it.
// Client-Side Code
var myCollection = {
"data": [
]
};
// Server-Side Code
protected void myButton_Click(object sender, EventArgs e)
{
// Parse JSON
}
Each item in the collection is stored in the "data" property. How do I loop through the JSON collection on the server-side? I thought about putting the JSON data in a Hidden HTML Element, but this didn't sound good and I could think of a good way to do it.
Thank you
How you send it to the server is up to you - a hidden field, an AJAX call, whatever you prefer. Once you've got the string on the server, you'll need 2 things:
A C# server-side representation
of that object
A converter to go
from JSON to that C# representation.
Let's adjust your example a bit, because "myCollection" in your example is an object, not a collection. So we'll call it myObject. Secondly, we'll assume that "data" is an array of strings. It could be anything, but we'll keep it simple.
var myObject = {
data: ["string1","string2"]
};
We'll also assume you're using the DataContractJsonSerializer, so you can easily map the two different case-styles...JavaScript is typically camelCase, and C# is typically ProperCase. So, in C#, this would be:
[DataContract(Name="myObjectType")]
public class MyObjectType{
[DataMember(Name="data")]
public string[] Data { get; set; }
}
Now you have two representations of the same structure, one in c#, one in JavaScript. To convert from one to the other, we can use the built-in DataContractJsonSerializer, like this:
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
...resulting in a final call of:
MyObjectType myObject = Deserialize<MyObjectType>(incomingString);
JSON in the Hidden Field is a valid way to do it, as the data would then be posted to the server. You could then use the System.Web.Script.Serialization.JavaScriptSerializer component to deserialize the data (to a dictionary) and access the data that way. Not 100% sure hhow array data comes out of that process. THere are also other tools like JSON.NET too to parse JSON.
Another way is via a web service call, but that doesn't go through the page lifecycle.
HTH.