How to serialize a JsonArray with C#? - c#

SO I have a Json array as following:
{[data, [{"name":"Micheal Jackson","pic_large":"https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"}
How can I serialize it with C# to parse it into objects and then pass it to the view.
EDIT:
{[data, [{"name":"Sayed Zubair Hashimi","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"},{"name":"Junaid Walizada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14055012_1760562554217155_4937121194048198140_n.jpg?oh=376b49c9d04c2676ebe3d853b122165e&oe=58EA033D","id":"1821833754756701"},{"name":"Mohib Akhondzada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/s200x200/14264218_592094647641140_6351146344336469735_n.jpg?oh=a8a63893d71f76c45fa3d07389f1700a&oe=59147C84","id":"648198542030750"},{"name":"Za Beah","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15741112_359701871054520_6692094260041596196_n.jpg?oh=6d9a0e73f70145b821c79cbe738090a0&oe=58E5B5B5","id":"360411140983593"},{"name":"Baser Nader","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15094436_10153876544626432_1550234361821853528_n.jpg?oh=e197fa712b3180a20612ecdacb01747c&oe=58E54DEC","id":"10153975726331432"},{"name":"Abasin Deniz","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15698075_440749809647293_7905213567074684088_n.jpg?oh=aeb22664f458d75fc00638ca6fa4ecfc&oe=591F7BB3","id":"444098429312431"}]]}
EDIT2:
Here is how I retrieve above Json.
var appsecret_proof = access_token.GenerateAppSecretProof();
var fb = new FacebookClient(access_token);
dynamic myFeed = await fb.GetTaskAsync(
("me/feed?fields=likes{{name,pic_large}}")
.GraphAPICall(appsecret_proof));

The strings shown in your question are all invalid JSON. A properly formatted JSON might look like this:
{
"data": [{
"name": "Micheal Jackson",
"pic_large": "https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938",
"id": "10154729171332597"
}]
}
Now if you want to map this to C# class that's pretty easy to do. Just define the models to reflect this structure:
public class Feed
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("pic_large")]
public string PicLarge { get; set; }
}
public class Result
{
[JsonProperty("data")]
public IList<Feed> Feeds { get; set; }
}
and then all that's left is to deserialize the JSON string using a JSON serializer such as Json.NET back to this object structure:
string json = ... the json string shown above
var result = JsonConvert.DeserializeObject<Result>(json);
foreach (var feed in result.Feeds)
{
Console.WriteLine(feed.Name);
}

first you need to create class with properties same as in json and then use the following code :
class obj
{
public string name {get ; set; }
public string pic_large {get ; set; }
public id {get ; set; }
}
using System.Web.Script.Serialization;
.
.
var obj = new JavaScriptSerializer().Deserialize<obj>(jsonString);

Related

Getting empty(blank) value while printing JSON field (value) using JsonConverter.Deserialize in C#

I am trying to parse a JSON using NewtonSoft (my JSON is an array type). Below is what it looks like...
{
"steps": [
{
"stepsType": "runWizard",
"wizardType": "demoServer",
"config": {
"mode": "add",
"resourceName": "demo server 1",
"activeDbPrimaryServer": {
"serverName": "abc",
"serverAddress": "abc.demo.local"
},
"activeDbCatalog": "demoActiveDB",
"activeDBUserId": "sa",
"activeDBPassword": "xyz",
}
}
]
}
I have created a class using JsonToC# convertor....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServerSetupWizardConsoleApp
{
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class ActiveDbPrimaryServer
{
public string serverName { get; set; }
public string serverAddress { get; set; }
}
public class Config
{
public string mode { get; set; }
public string resourceName { get; set; }
public ActiveDbPrimaryServer activeDbPrimaryServer { get; set; }
public string activeDbCatalog { get; set; }
public string activeDBUserId { get; set; }
public string activeDBPassword { get; set; }
}
public class Step
{
public string stepsType { get; set; }
public string wizardType { get; set; }
public Config config { get; set; }
}
public class Root
{
public List<Step> steps { get; set; }
}
}
And now when I am trying to deserialise it in another class, I am getting a empty response in console...
I have a TEXT from where I am reading the JSON and then storing it in a string type variable and the using the string to deserialise it.
public Object ReadJson()
{
string jsonText = File.ReadAllText("C:\\Desktop\\demo.json");
var rootObject = (Root) JsonConvert.DeserializeObject(jsonText, typeof(Root));
var activeDbAttr = (ActiveDbPrimaryServer)JsonConvert.DeserializeObject(jsonText, typeof(ActiveDbPrimaryServer));
Console.WriteLine("Value : " + activeDbAttr.serverAddress);
}
This activeDbAttr.serverAddress is giving me nothing in CONSOLE
It print --> value : (nothing after ":" like blank)
Can someone tell me what is wrong here. I followed some old answers, not getting to a point where I can fix it.
Live demo : https://dotnetfiddle.net/PuO8F8
It's a simple navigation issue.
You deserialize to a Root object, and instead of navigating with the property you deserialize again into an other thing, hopping to land in the right place.
var rootObject = JsonConvert.DeserializeObject<Root>(jsonText);
var activesDBs = json.steps.Select( x=> x.config.activeDbPrimaryServer).ToList();
Result:
Dumping object(System.Linq.SelectListIterator`2[Step,ActiveDbPrimaryServer])
[
{
serverAddress : abc.demo.local
serverName : abc
}
]
Why did it failed ?
var jsonDB = JsonConvert.DeserializeObject<ActiveDbPrimaryServer>(GetJson());
Tell the Parser that the Json is of type ActiveDbPrimaryServer.
The parser open the Json and find the first object:
{
"steps": [..]
}
Look for the property of the expected type ActiveDbPrimaryServer
public class ActiveDbPrimaryServer
{
public string serverName { get; set; }
public string serverAddress { get; set; }
}
And find nothing. It end there and give you an object of the right type with no property initialized
Partial deserialization:
If you want to deserialize only the part you need, refer to this documentation from Newtonsoft:
Deserializing Partial JSON Fragments
JObject rootObj = JObject.Parse(GetJson());
// get JSON result objects into a list
IList<JToken> results = rootObj["steps"].Children() // Step is a list so we use `.Children()`
["config"]["activeDbPrimaryServer"].ToList();
IList<ActiveDbPrimaryServer> dbResults = new List<ActiveDbPrimaryServer>();
foreach (JToken result in results)
{
// JToken.ToObject is a helper method that uses JsonSerializer internally
ActiveDbPrimaryServer dbResult = result.ToObject<ActiveDbPrimaryServer>();
dbResults.Add(dbResult);
}
you are deserializing
var rootObject = (Root) JsonConvert.DeserializeObject(jsonText, typeof(Root));
var activeDbAttr = (ActiveDbPrimaryServer)JsonConvert.DeserializeObject(jsonText, typeof(ActiveDbPrimaryServer));
[the second one yields null ... and null cast to ActiveDbPrimaryServer yields null.]
the same string twice into 2 different types of objects that do not share common base class (of course other than object).
your text represents either a Root or a ActiveDbPrimaryServer not both. the ActiveDbPrimaryServer is a member of the config class and that in turn of Step. ....
step through your graph root.Step.Config .. if all the instances are set you should reach your instance of ActibeDdPrimaryServer

Using JSON.net define class with array in Dictionary

I am trying to do the following inside a Dictionary<string,string>
{
"name": "Bob Barker",
"devName": "InformationServices",
"ReturnedData": [{
"level_heading": "blah1",
"DeliverBestMedicalValue": "blah2",
"level_question": "blah3"
}]
}
I can add the name and devName just fine but I am unsure on how to go about adding the ReturnedData part of the array to the list so that it will return as the layout above?
Example code I am using:
febRecords.RootObject febRecordsData = JsonConvert.DeserializeObject<febRecords.RootObject>(serverResponse);
Dictionary<string,string> febFormData = new Dictionary<string,string>();
febFormData.Add("name", data.firstname.ToString());
febFormData.Add("devName", febData["Data"]["DevisionName"].ToString());
febFormData.Add("ReturnedData", ???); //<-this is where I am stuck
return Ok(JsonConvert.SerializeObject(febFormData, Newtonsoft.Json.Formatting.Indented));
As you see, febFormData.Add("ReturnedData", ???); is the spot where I am stuck and dont really know what to do in order to get the dictionary to output the correct JSON format like I want.
Any help would be great!
update
Would this be how the class needs to look?
public class theOutput
{
public string name { get; set; }
public string devName { get; set; }
public List<string> ReturnedData { get; set; }
}
As suggested by #Panagiotis Kanavos you'd really be better off having .NET entity to match your JSON data. For example:
// propertyname attributes can be ignored if property names
// match the json data property names 1:1
[JsonObject]
public class MyClass
{
public MyClass()
{
ReturnedData = new List<ReturnedData>();
}
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "devName")]
public string DevName { get; set; }
[JsonProperty(PropertyName = "ReturnedData")]
public List<ReturnedData> ReturnedData { get; set; }
}
[JsonObject]
public class ReturnedData
{
[JsonProperty(PropertyName = "level_heading")]
public string LevelHeading { get; set; }
[JsonProperty(PropertyName = "DeliverBestMedicalValue")]
public string DeliverBestMedicalValue { get; set; }
[JsonProperty(PropertyName = "level_question")]
public string LevelQuestion { get; set; }
}
This would make conversion to/from JSON that much easier.
[TestMethod]
public void TestSome()
{
string json = #"{
""name"": ""Bob Barker"",
""devName"": ""InformationServices"",
""ReturnedData"": [{
""level_heading"": ""blah1"",
""DeliverBestMedicalValue"": ""blah2"",
""level_question"": ""blah3""
}]
}";
var obj = JsonConvert.DeserializeObject<MyClass>(json);
Assert.IsTrue(JToken.DeepEquals(JObject.Parse(json), JObject.FromObject(obj)));
}
You can always generate stubs from you JSON data using e.g. http://json2csharp.com/
Here "live" .NET fiddle, too https://dotnetfiddle.net/9ACddp

Parse the fetched data in C#

I am new to C# and trying to write some code to fetch the webpage and parse it into readable format.
I have fetched the data from webpage using uri
var uri2 = new Uri("explame.com")
I see the response in format below like this:
{"name":"abc" "country":"xyz" "citizenship":"A" [{"pincode":"111", "Dis":"no"] Lot's of data follows something like that
There are multiple with attribute "name" and "country" in response. My question is how to fetch the data something like below
name:abc
country:xyz
citizenshih:A
pincode 111
dis:no
For all attributes in response code.
Is that the exact format of the data you're getting? Because that's JSON-ish, but it's not valid JSON and wouldn't be parsed as such. If, however, you are actually getting JSON then you can de-serialize that.
Using something like Newtonsoft's JSON library you can fairly trivially de-serialize JSON into an object. For example, this JSON:
{
"name":"abc",
"country":"xyz",
"citizenship":"A",
"someProperty": [
{
"pincode":"111",
"Dis":"no"
}]
}
Might map to these types:
class MyClass
{
public string Name { get; set; }
public string Country { get; set; }
public string Citizenship { get; set; }
public IEnumerable<MyOtherClass> SomeProperty { get; set; }
}
class MyOtherClass
{
public string Pincode { get; set; }
public string Dis { get; set; }
}
In which case de-serializing might be as simple as this:
var myObject = JsonConvert.DeserializeObject<MyClass>(yourJsonString);
you could try
dynamic data = JsonConvert.DeserializeObject(receivedJsonString);
foreach (dynamic o in data)
{
Debug.WriteLine(o.country);
}

Get specific part of json object which has a certain value

I'm trying to get a specific part of Json, but couldn't figure out how.
My json looks like:
[
{
"ResourceId":"1",
"ResourceText":"Hello",
"LanguageId":"1"
},
{
"ResourceId":"2",
"ResourceText":"World",
"LanguageId":"1"
}
.
.
.
]
So for example I want the part (changes according to pResourceId parameter, so what I'm trying to get changes everytime)
{
"ResourceId":"1",
"ResourceText":"Hello",
"LanguageId":"1"
}
But I couldn't get it. What I tried so far:
JObject data = JObject.Parse(jsonStringResources);
return data.Values().Where(x => x.Contains("ResourceId\" : \"" +pResourceId +"\"") ) as clsResource;
I would make a model for the format of your JSON:
class Model
{
public string ResourceId { get; set; }
public string ResourceText { get; set; }
public string LanguageId { get; set; }
}
And then you can do:
var models = JsonConvert.DeserializeObject<List<Model>>(jsonStringResources);
var matchingModel = models.Where(model => model.ResourceId == pResourceId).ToList().FirstOrDefault();
return JsonConvert.SerializeObject(matchingModel);
We deserialize the JSON into a list of our models. We then get the model where the ResourceId matches the pResourceId. Finally, we serialize the model again to get the JSON string.
When pResourceId == 1, the result is:
{
"ResourceId": "1",
"ResourceText": "Hello",
"LanguageId": "1"
}
If your json looks like that, you can deserialize it into object which would be:
public class JsonTestModel
{
public JsonTestModel()
{
}
public int ResourceId { get; set; }
public string ResourceText { get; set; }
public int LanguageId { get; set; }
}
and then you could search for it like this:
List<JsonTestModel> theListWithModels = JsonConvert.DeserializeObject<List<JsonTestModel>>(theJsonString);
var extractedModels = theListWithModels.Where(m => m.ResourceId == pResourceId);

Store a JSON string in C# and then access individual parts of it

I am pulling some JSON from an API. It comes in this format:
{"yourname": {
"id": 42728521,
"name": "Your Name",
"profileIconId": 27,
"revisionDate": 1397930999000,
"summonerLevel": 1
}}
However, that is stored as:
"{\"yourname\":{\"id\":42728521,\"name\":\"Your Name\",\"profileIconId\":27,\"summonerLevel\":1,\"revisionDate\":1397930999000}}"
Inside the string.
I want to be able to call summonerLevel and for it to return the correct value.
I've been trying this:
using (var client = new WebClient())
{
api_return = client.DownloadString(api_call_key);
}
var foo = JsonConvert.DeserializeObject<Summoner>(api_return);
Console.WriteLine(Summoner.id);
Console.WriteLine(Summoner.name);
Console.WriteLine(Summoner.summonerLevel);
string id_ = foo.ToString();
Console.WriteLine(id_);
Console.ReadKey();
}
public class Summoner
{
public static int id { get; set; }
public static string name { get; set; }
public static int summonerLevel { get; set; }
}
However, that just prints out:
0
nothing
0
You have two issues here, which are both preventing you from getting the data from the JSON.
The first issue is that the properties of your Summoner class should not be static, as Vikas pointed out. Define your class like this:
public class Summoner
{
public int id { get; set; }
public string name { get; set; }
public int summonerLevel { get; set; }
}
The second issue is that your JSON structure doesn't match what you're deserializing into. The id, name and summonerLevel properties are not at the root level of the JSON, they are one level further down, inside another object. So, you'll need to deserialize into some class that "wraps" your Summoner. If the yourname property in the JSON were a fixed value, you could define a Wrapper class like this to deserialize into:
public class Wrapper
{
[JsonProperty("yourname")]
public Summoner Summoner { get; set; }
}
However, since the yourname property in the JSON is likely not a fixed value (it could change for different summoners), I would recommend deserializing into a Dictionary<string, Summoner> like this instead:
var dict = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(json);
From there, you can either loop through the dictionary key-value pairs, or, if you're only expecting one, you can use First() to get it.
var summoner = dict.First().Value;
Here is a full demo:
string json = #"{""yourname"": {
""id"": 42728521,
""name"": ""Your Name"",
""profileIconId"": 27,
""revisionDate"": 1397930999000,
""summonerLevel"": 1
}}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(json);
var summoner = dict.First().Value;
Console.WriteLine(summoner.id);
Console.WriteLine(summoner.name);
Console.WriteLine(summoner.summonerLevel);
Output:
42728521
Your Name
1
Properties in Summoner class should not be static
using (var client = new WebClient())
{
api_return = client.DownloadString(api_call_key);
}
var foo = JsonConvert.DeserializeObject<Summoner>(api_return);
Console.WriteLine(foo.id);
Console.WriteLine(foo.name);
Console.WriteLine(foo.summonerLevel);
..............
}
public class Summoner
{
public int id { get; set; }
public string name { get; set; }
public int summonerLevel { get; set; }
}

Categories

Resources