parse Json text to C# object in asp mvc 4 - c#

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);

Related

Convert string to json using C#

i am beginner to C#, i have a very long string and want to convert it to json, string is
{"employees":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
\
any ideas?
You can do something like this:
var jobject = JsonConvert.DeserializeObject<JObject>(yourVariable);
this is using Newtonsoft's json library that you can get from nuget.
Also JObject is the C# equivalent to a JSON object so that's probably something you'll want to use.
u an also use,
JObject.Parse(urJsonString);
JObject is in Newtonsoft.Json.Linq namespace.
You need to Deserialize your string as follows :
// Your string here
string str = #"[{"categories":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
{"id":0,"level":0,"label":"Product texts","subitems":
[{"id":0,"level":1,"label":""},{"id":0,"level":1,"label":"<p>Disney <strong>Princess<\/strong><\/p>\n"},{"id":0,"level":1,"label":"<p>Machines & Mechanisms - <strong>Middle<\/strong><\/p>\n"},{"id":0,"level":1,"label":"64738574"},{"id":0,"level":1,"label":"8765432"},{"id":0,"level":1,"label":"a"},{"id":0,"level":1,"label":"aa"},{"id":0,"level":1,"label":"ab"},{"id":0,"level":1,"label":"abe"},{"id":0,"level":1,"label":"aD!?"},{"id":0,"level":1,"label":"Bionicle"},{"id":0,"level":1,"label":"Disney Princess"},{"id":0,"level":1,"label":"er"},{"id":0,"level":1,"label":"foo foo"},{"id":0,"level":1,"label":"hej"},{"id":0,"level":1,"label":"igen"},{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"metadata"},{"id":0,"level":1,"label":"metadata from kafka"},{"id":0,"level":1,"label":"Metatest"},{"id":0,"level":1,"label":"q"},{"id":0,"level":1,"label":"Simpsons"},{"id":0,"level":1,"label":"test"},{"id":0,"level":1,"label":"Test 123"},{"id":0,"level":1,"label":"Test Metadata 123"}]},{"id":0,"level":0,"label" :"Specialist Terms","subitems":[{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"new category 1111"},{"id":0,"level":1,"label":"secret category"}]}]}]";
// DeSerialize your object
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Converting json string into list of existing object in C#

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?

How to add a parent to every child in a json array?

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.

javascript object load values as in C# dictionary (and pass it as a dictionary<string,string>)

I could see many of them questions the opposite direction
my question is how could i pack up values ?
var KeyName = "name" or.. $(ControlId).attr("id")
var ValName = $(ControlId).val()
then with ajax post that value after of course serializing it (if it is required)
var CS_Pckg = Sys.Serialization.JavaScriptSerializer.serialize(DictionaryLike_Package);
ajaxPost(CS_Pckg);
...some ajax function
is it like an array ?
jQuery has a "serialize" method that you can use for serialization of HTML forms: http://api.jquery.com/serialize/
However, that method serializes to a GET string; if you instead want a set of name/value pair objects, checkout serializeArray: http://api.jquery.com/serializeArray/
If neither of those produces the output you want, you pretty much just have to do the serialization yourself. You can use jQuery's each method to iterate through a set of elements, and then you can extract any information you want out of them. Once you're done and you have a single Javascript object with all the data in it, you can convert that object to a string using JSON.stringify(thatObject);.
Here's a quick example:
var serializedData = {};
$('#yourForm').children().each(function(i, elem) {
var $elem = $(elem);
serializedData[$elem.attr('name')] = $elem.val();
});
alert("You're serialized JSON is: " + JSON.stringify(serializedData));
(No example for the earlier options, because they're as simple as var serialized = $('#yourForm').children().serialize();.)

converting list to json format - quick and easy way

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);
}

Categories

Resources