Deserializing Json to get data directly and not through loop - c#

I see many different ways to deserialize Json and I think I am using the quickest method for my solution yet I have to do cartWheels to get to the data I want is there a better way to get the data I want from a JSON object ?
private static void stillAttemptToParse()
{
var client = new WebClient();
var response = client.DownloadString(new Uri("http://localhost:52644/api/status"));
var j = JsonConvert.DeserializeObject<Status>(response);
//Status is a group of classes to represent the data from jsonToC#
Console.WriteLine(j.OverallSuccess);
foreach (var item in j.SettingItems)
{
Console.WriteLine("id: {0}, : {1} : {2}" , item.SettingName, item.Source , item.SettingValue);
}
}
So the real question would be if i know the item.SettingsName is 'basicURL' how can I get the item.SettingsValue( which would be http://www.someBasicUrl.com ) for that item 'basicUrl' without running a loop ?

Take a look at Newtonsoft's json DeserializeObject(). Their Json.NET library is pretty good.
http://www.newtonsoft.com/json/help/html/deserializeobject.htm
Hope this helps!

Related

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?

Parse Dynamic JSON string

I am getting a JSON response from a server but the JSON is not in a one format. So obviously there is no point of creating classes to deserialize it. So, I tried to use dynamic but I am unable to read the response.
The sample JSON String is
" {"hm_xytrict":"HM Tricky District - oop","hmSD":"HM Pool District"}"
Note that "hm_xytrict" and "hmSD" will be different every time
I am using
dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);
For this specific case I can use jsonResponse.hm_xytrict and jsonResponse.hmSD but since they are also dynamic so how can I read jsonResponse for all cases.
Thank you,
Hamza
So you can use a different part of the JSON.NET api to parse and extract data from your object:
var jObj = JObject.Parse(json);
foreach (JProperty element in jObj.Children())
{
string propName = element.Name;
var propVal = (string)element.Value;
}
Even more interesting, you can directly parse a JSON string to a dynamic object
string responseString = #"{""hm_xytrict"":""HM Tricky District - oop"",""hmSD"":""HM Pool District""}";
dynamic jsonResponse = JObject.Parse(responseString);
foreach (var item in jsonResponse)
{
Console.WriteLine(item.Name);
Console.WriteLine(item.Value);
}
Which in your example will output
hm_xytrict
HM Tricky District - oop
hmSD
HM Pool District

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.

Converting a Javascript JSON.stringfy string to an object using c# JSON.NET

I am developing a windows 8 app, and i have some javascript that stores a serialized object into roaming settings, i.e:
var object = [{"id":1}, {"id":2}]
roamingSettings.values["example"] = JSON.stringify(object);
I also i have a c# part to the application (for running a background task), that needs to read that JSON, and turn it into an object so i can iterate over it. And this is where i am having some issues, i am using JSON.NET to do the work, but every thing i turn turns up with an error:
// this looks like "[{\"id\":1},{\"id\":2}]"
string exampleJSON = roaming.Values["example"].ToString();
// dont know if this is correct:
List<string> example = JsonConvert.DeserializeObject<List<string>>(exampleJSON );
That give an error of:
Error reading string. Unexpected token: StartObject. Path '[0]', line 1, position 2.
So i am at a loss of what to do, i have been working on it for last few hours, and i am quite unfamiliar with c#, so resorting to the help of stackoverflow ;D
Thanks in advance for any help :)
Andy
Json.Net has a nice method DeserializeAnonymousType. No need to declare a temporary class.
string json = "[{\"id\":1},{\"id\":2}]";
var anonymous = new []{new{id=0}};
anonymous = JsonConvert.DeserializeAnonymousType(json,anonymous);
foreach (var item in anonymous)
{
Console.WriteLine(item.id);
}
You can even use the dynamic keyword
dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var item in dynObj)
{
Console.WriteLine(item.id);
}
You are trying to parse your JSON array into a List of strings, which doesn't work. The JSON object you provide is actually a list of objects containing an integer property called 'id'.
Perhaps try creating a class (say, MyClass) with just that property, and deserialize into List.
Your json containts a collection of objects with an id property, something like this:
class IdObject {
public int id { get; set; }
}
You could then do:
JsonConvert.DeserializeObject<List<IdObject>>(exampleJSON);
Because the IdObject class has a property id to match your json serialized value, it will be mapped back.

parse Json text to C# object in asp mvc 4

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

Categories

Resources