Let's say I have an object MyObject that looks like this:
public class MyObject
{
int ObjectID {get;set;}
string ObjectString {get;set;}
}
I have a list of MyObject and I'm looking to convert it in a json string with a stringbuilder. I know how to create a JavascriptConverter and create a json string by passing a list and having the converter build the string but in this particular case I'm looking to avoid the overhead and go straight to a json string with a foreach loop on the list like this:
StringBuilder JsonString = new StringBuilder();
foreach(MyObject TheObject in ListOfMyObject)
{
}
I've tried to use this method by appending with commas and quotes but it hasn't worked out (yet).
Thanks for your suggestions.
I've done something like before using the JavaScript serialization class:
using System.Web.Script.Serialization;
And:
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();
3 years of experience later, I've come back to this question and would suggest to write it like this:
string output = new JavaScriptSerializer().Serialize(ListOfMyObject);
One line of code.
For me, it worked to use Newtonsoft.Json:
using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);
I would avoid rolling your own and use either:
System.Web.Script.JavascriptSerializer
or
JSON.net
Both will do an excellent job :)
why reinvent the wheel? use microsoft's json serialize or a 3rd party library such as json.NET
I prefer using linq-to-json feature of JSON.NET framework. Here's how you can serialize a list of your objects to json.
List<MyObject> list = new List<MyObject>();
Func<MyObject, JObject> objToJson =
o => new JObject(
new JProperty("ObjectId", o.ObjectId),
new JProperty("ObjectString", o.ObjectString));
string result = new JObject(new JArray(list.Select(objToJson))).ToString();
You fully control what will be in the result json string and you clearly see it just looking at the code. Surely, you can get rid of Func<T1, T2> declaration and specify this code directly in the new JArray() invocation but with this code extracted to Func<> it looks much more clearer what is going on and how you actually transform your object to json. You can even store your Func<> outside this method in some sort of setup method (i.e. in constructor).
You could return the value using
return JsonConvert.SerializeObject(objName);
And send it to the front end
If you are using WebApi, HttpResponseMessage is a more elegant way to do it
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}
Related
I work with an api, that returns a json formatted resultset of a database query.
I have an equivalent object or "model" for the results.
What is the best way to convert the json string into a list of this object?
Of course there are many threads about this, but no one fits my needs properly.
One of the solutions I've found was this:
var jobj = (JObject)JsonConvert.DeserializeObject(json);
var items = jobj.Children()
.Cast<JProperty>()
.Select(j => new
{
ID = j.Name,
Topic = (string)j.Value["Topic_ID"],
Moved = (string)j.Value["Moved_ID"],
Subject = (string)j.Value["subject"],
})
.ToList();
This seems pretty close to what I need. I need to be able to map the keys/values to the appropriate object attributes, which DOES already exist. So maybe you only need to change a few things to make it work for my object?
PS: I'm using Newtonsoft. Any solution for .NET or Newtonsoft or if needed any other library would be great!
I have recently been consuming data from a WebApi and i have been using the following code to convert the json object to an object to work with:
using (var client = new HttpClient())
{
var response = client.GetAsync(apiUri).Result;
// For single objects.
MyObject data = response.Content.ReadAsAsync<MyObject>().Result;
// For an array of objects
IEnumerable<MyObject> data = response.Content.ReadAsAsync<IEnumerable<MyObject>>().Result;
}
Hope this helps.
OK, so you have something like this:
public class MyObject
{
public int ID {get; set;}
public string Topic {get; set;}
public string Subject {get; set;}
}
And you want to instantiate an array of MyObjects with the properties coming from your JSON?
In that case you're just a bout there - you're currently creating a dynamic object with the same properties as MyObject, right? So all you need to do is create an actual MyObject instead:
.Select(j => new **MyObject()**
{
ID = j.Name,
Topic = (string)j.Value["Topic_ID"],
Moved = (string)j.Value["Moved_ID"],
Subject = (string)j.Value["subject"]
})
Note that if your json property names exactly match your C# ones (including case), you can do this as a one-liner with NewtonSoft: http://www.newtonsoft.com/json/help/html/SerializingJSON.htm. But to use that method you'd have to have an intermediate C# class to match your JSON, and then automap (or manually convert) those to MyObjects. Or you'd have to make sure your json and c# properties match exactly. But you're already very close to a quicker (though some would argue less elegant) solution.
Why aren't you deserializing the json into the object type directly? you can do it like this...
var obj = (YourType)JsonConvert.DeserializeObject(
json,
typeof(YourType),
new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto,
MissingMemberHandling=MissingMemberHandling.Ignore
});
or am I missing something in the question?
I'm working on a Web Service in ASP.NET that has two methods, what I want to do is to return the data in JSON format, I'm usin JSON.NET library.
This is one of the methods:
[WebMethod]
public string GetReservas()
{
var json = "";
var data = from result in DCHotel.visHTLReservaciones select result;
json = JsonConvert.SerializeObject(data);
return json;
}
When I run the web service, this is the output in my browser:
[{"id":1,"name":"jose","age":22},{"id":2,"name":"john","age":21}]
And what I need is something like this:
["person":[{"id":1,"name":"jose","age":22}],"person":[{"id":2,"name":"john","age":21}]]
I need to add parents to every child in the array, I don't know how to do it, and I searched a lot and can't find the solution to this, hope you can help me.
Thanks.
It's very easy, change your linq query to this:
var data = from result in DCHotel.visHTLReservaciones select new { person = result };
Instead of taking just the result you encapsulate it on an anonymous class.
Cheers.
I have a json string that has multiple class types. I want to be able to parse the json file and also cast the objects dynamically.
Example:
object jsonInstanceOfObject = LitJson.JsonMapper.ToObject<Type.GetType(classTypeString)>(jsonString);
Is this even possible?
First, determine the object structure from the json string. And you can do that either yourself by looking at it or you can also use the tool json2csharp.com (also mentioned above by L.B)-its really a handy too. It saves you time.
Once you know what the class structure corresponding to the json string is going to be, lets call it T for now, the following will do it.
private async Task<T> ParseJsonToObjectAsync(string jsonValue)
{
var obj = await JsonConvert.DeserializeObjectAsync<T>(jsonValue);
return obj;
}
If you are not using async,you can use this:
private T ParseJsonToObject(string jsonValue)
{
var obj = JsonConvert.DeserializeObject<T>(jsonValue);
return obj;
}
And that json serializer/deserializer is part of Newtonsoft.Json
Hope it helps.
Happy coding :)
I have a DynamicJsonObject like:
var obj = new DynamicJsonObject();
obj.Field1 = "field1";
obj.Field2 = "field2";
I need the obj's json string. I tried using JavaScriptSerializer:
var json = JavaScriptSerializer.Serialize(obj);
But the result is always json == '{}'
Is there a workaround for this? preferably not using third party libraries
You can add custom converter to JavaScriptSerializer. In System.Web.Helpers one already exists but is internal - you can use the following code to register it:
var type = Type.GetType("System.Web.Helpers.DynamicJavaScriptConverter, System.Web.Helpers");
var converter = (JavaScriptConverter)Activator.CreateInstance(type);
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { converter });
var json = serializer.Serialize(obj);
or copy code from here
Thanks for your answers, but I've found a simple way to do this by using System.Web.Helpers.Json.
So, my code looks like this:
string json = Json.Encode(obj);
I cannot use an anonymous object, because I don't create obj, it is provided in the DynamicJsonObject 'format' already.
I have a huge amount of customized attributes I want to save them in the DataBase, I was confused of how to store them in the database, i thought of storing them as a string separating them by
(= => name , value) (; => attribute , attribute) but the code wasn't elegant at all!
so i stat thinking of saving them as Json string but I couldn't found a
Json to object parser
while we need only to call json() to parse object to json string
is there a better way than using json string and is there json string parser provided ?
Try to use System.Web.Script.Serialization.JavaScriptSerializer, here is example:
var yourObject = new JavaScriptSerializer().Deserialize<YourType>(strInput)
or
var yourObject = new JavaScriptSerializer().Deserialize(strInput)
Many people use Json.net for serialization
var log = JsonConvert.DeserializeObject<YourObject>(logJson)
and the other direction
var logJson = JsonConvert.SerializeObject(log);
You can use $.parseJSON, try this just for you to see the txt data:
var info = $.parseJSON(data);
alert(info);