Trying to parse data from a website and deserializing it in C# - c#

I'm trying to parse data from my website and then deserializing it inside C# but I haven't gotten it work. What is the simplest way and method to use when grabbing data from a http source and deserializing it in C#?

Based on the following JSON:
{
name: "Brad Christie",
score: 10,
questions: [
{
question_id: 1,
question: "How do I deserialize javascript?",
answer: "JavaScriptSerializer",
points: 10
}
]
}
and assuming these classes:
public class Question
{
public Int32 question_id;
public String questions;
public String answer;
public Int32 points;
}
public class JSExample
{
public String name;
public Int32 score;
IEnumerable<Question> questions;
}
the below should work (though didn't test and going by memory of what I've done in the past). Basically, the JavaScriptSerializer should take a JSON string and parse it out in to your custom object, or result in a dictionary of the structure of the JSON (I personally prefer placing it an object so i can manipulate it as I chose, but you can use the dictionary/dynamic variable and debug to see the result). Anyways, the code would be as follows:
//String the_JSON_string = <data from webpage>;
JavaScriptSerializer serializer = new JavaScriptSerializer();
JSExample example = serializer.Deserialize<JSExample>(the_JSON_string);

There are a number of JSON serializers in .NET. Most notably the built in DataContractSerializer
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
EDIT:
(Sorry wrong link, here's the one for JSON
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
and http://msdn.microsoft.com/en-us/library/bb410770.aspx)
and JSON.NET
http://json.codeplex.com/

Related

Dynamically reading .json file with multiple objects

An application is providing me a .json file that contains an unknown amount of objects. On top of that, the objects content also changes quite a bit.
Here is an example of a json file:
{
"AVRunning":{
"Description":"Symantec Antivirus Service",
"Status":true
},
"CorrectOU":{
"Description":"Server in Correct OU",
"Status":true
},
"RoleAdGroups":{
"Result":true,
"Group":"Server-Admin"
},
"DefaultAdGroups":[
{
"Result":true,
"Group":"Domain Admins"
},
{
"Result":true,
"Group":"Server-Admins"
},
{
"Result":true,
"Group":"SERVERNAME-ADMINS"
}
]
}
This is just an example of a json file. It could contain many more objects, as well as an unknown amount of content within it.
My question to you all, is how do I serialize this into a JSON object in c# once I read the content in as one gigantic string?
Also, I may be overcomplicationg the process here. Once I read this in, I want to pass the data to my view. If this can't be done in c#, would it be easier to do it in Jquery? Or should it be done there in the first place? The file that I am reading in is a local file, so I can't access the data directly in jquery.
I know JSON.NET is a possible tool, but from what I have read, I am not sure how to create the objects dynamically.
You have to define data types into which you want to deserialize json string:
public class ObjectWithDescriptionAndStatus
{
public string Description;
public string Status;
}
public class ObjectWithResultAndGroup
{
public bool Result;
public string Group;
}
public class MyObject
{
public ObjectWithDescriptionAndStatus AVRunning;
public ObjectWithDescriptionAndStatus CorrectOU;
public ObjectWithResultAndGroup RoleAdGroups;
public IList<ObjectWithResultAndGroup> DefaultAdGroups;
}
This is the simplest example, with all fields marked as public and named exactly as keys in the json (they can have arbitrary names but in that case you have to decorate each field with DataMember attribute and set its Name property to the actual name of the key).
Having data types defined, deserialization is a one-liner:
MyObject myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(json);
jQuery makes it pretty simple (just jQuery.parseJSON(<your string>);).
I imagine JSON.NET has a parse function as well, but I haven't used that library, so I couldn't say for sure!

handling JSON response that is not the same each time

i am working with json.net to deserialize json -> C# objects.
it works great in most cases but there are times where rather than getting an array i get object.
so my class (generated using http://json2csharp.com/ and modified to add property).
where i more than 1 arrival methods (such as pick up or ship) it works fine.
public class ArrivalMethods
{
[JsonProperty(PropertyName = "ArrivalMethod")]
public List<string> ArrivalMethod { get; set; }
}
but it breaks where there only 1 arrival method in the json response from my service because i believe json.net is expecting an object like below.
public class ArrivalMethods
{
[JsonProperty(PropertyName = "ArrivalMethod")]
public string ArrivalMethod { get; set; }
}
i am new to json etc. so i am not sure what i am doing wrong. but this throws exception.
Error converting value \"Ship\" to type 'System.Collections.Generic.List`1[System.String]'.
Path 'ProductDetail.SoftHardProductDetails.Fulfillment.
ArrivalMethods.ArrivalMethod', line 1, position 113."
here is where it breaks:
"ArrivalMethods":{
"ArrivalMethod":"Ship"
},
Your JSON should contain [] where there is a list. And if I'm understanding your answer correct, the first class example is the way you want to end up? If so you need the JSON on the bottom to mark ArrivalMethod as a list, wich its not now.
"ArrivalMethods":
{
"ArrivalMethod":["Ship"]
},
To be honest i get a little confused when there is a list with no plural ending.
If you can change the response format that would be the best. It really looks like XML semantics converted to JSON...
If you can't change the response format, you can try to use JsonConverterAttribute to create custom converters for those properties.

How read JSON file in C#? [duplicate]

I have about 7000 lines of JSON data that I want to parse. An example of just part of it can be seen here. What I did was use WebRequest and StreamReader to put all the data into a string. (Oddly, it puts all of the data into one VERY long line). But now I want to parse this and I am not sure how. Can anyone explain how to use Deserialize? I have parsed JSON data with Java before but I am having trouble doing so with C# especially with my inability to find documentation with clear examples. Any help will be greatly appreciated.
Try JSON.Net, if you have not seen this it should help you.
Json.NET library makes working with
JSON formatted data in .NET simple.
Key features include a flexible JSON
serializer to for quickly converting
.NET classes to JSON and back again,
and LINQ to JSON for reading and
writing JSON.
Deserialization discussed here.
The quickest method of converting
between JSON text and a .NET object is
using the JsonSerializer. The
JsonSerializer converts .NET objects
into their JSON equivalent and back
again.
The basic code structure for deserialization is below - Target still needs to be filled out to capture the rest of the parsed data items with the appropriate type. The file mentioned json.txt contains your data from the URL above.
using System;
using System.IO;
using Newtonsoft.Json;
public class NameAndId
{
public string name;
public int id;
}
public class Data
{
public NameAndId[] data;
}
public class Target
{
public string id;
public NameAndId from;
public Data likes;
}
public class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText(#"c:\temp\json.txt");
Target newTarget = JsonConvert.DeserializeObject<Target>(json);
}
}
Here is the first part of the JSON stream for reference:
{
"id": "367501354973",
"from": {
"name": "Bret Taylor",
"id": "220439"
},
"message": "Pigs run from our house in fear. Tonight, I am wrapping the pork tenderloin in bacon and putting pancetta in the corn.",
"updated_time": "2010-03-06T02:57:48+0000",
"likes": {
"data": [
{
"id": "29906278",
"name": "Ross Miller"
},
{
"id": "732777462",
"name": "Surjit Padham"
},
Personally I don't like carrying around dependencies on external libraries when the functionality is provided by the framework. In this case, the JavaScriptSerializer class:
var serializer = new JavaScriptSerializer();
var myobj = serializer.Deserialize<MyType>(mystring);

MVC 4 ApiController not serializing System.Json.JsonObject properly

So I am new to working with MVC4 and the serialization of objects on the back end seems pretty "magical" to me so if I am doing this the wrong way please let me know.
My goal however is to build a simple rest API and return JSON out. I figured that I would use System.Json and just return JsonObject. I have simplified this down for the sake of this question but the objects are much more complicated in my real issue.
Here is my controller....
....
public class ActionsController : ApiController
{
// GET api/actions
public JsonObject Get()
{
JsonObject testObjet = new JsonObject();
testObjet.Add("Name", "Test name");
testObjet.Add("Description", "Test Description");
return testObjet;
}
....
I would expect to see:
{"Name":"Test name","Description":"Test Description"}
Instead I see:
{"Name":[],"Description":[]}
I actually seem to get better results when I return a string of the JsonObject or heck even just return the object itself with the exception it has enums and I want to return the names not the number values, which is what led me to JsonObject for customization.
Does anyone know why it is dropping off the values?
EDIT:
So because of Dan's comments below I tried just for giggles to see what the XML serializer spit out with the JSON object and I get the below exception...
"Type 'System.Json.JsonPrimitive' with data contract name 'JsonPrimitive:http://schemas.datacontract.org/2004/07/System.Json' is not expected."
So it appears that you can not serialize the System.Json.JsonObject object, because it uses a type that it does not expect.
That is shocking. Does anyone have a workaround? If not I am off to find out how to show enum names when serializing instead of values.
So the answer is apparently... You Can't!
It appears that the type JsonPrimitive is not supported to serialize objects. The answers provided below by Obi and Dan helped me to poke around a bit more and find out that the XML serializer actually throws an exception while the JSON serializer simply eats it and puts out an empty array which is what you see above.
There are any number of correct answers here.
Make your own custom serializer
Output JSON as a string
Return custom objects and then work around things like the Enum
values
I am sure there are others.
But whatever you do don't try to use System.Json as a return in the ApiController because you will get the results above.
You should not force your WebApi call to use a particular format like JSON. One of the features of WebApi is that you can specify the format as part of the request. Return an object from your Get call, and let the WebApi engine do the serialization and deserialization:
public class DataObject
{
public string Name { get; set; }
public string Description { get; set; }
}
public class ActionsController : ApiController
{
// GET api/actions
public DataObject Get()
{
var testObject = new DataObject
{
Name = "Test name",
Description = "Test Description"
};
return testObject;
}
}
You can specify the format by setting the Accept header to application/xml, application/json, etc.
The default JSON serializer has no problem serializing simple string properties like Name and Description.
I would suggest you did this instead
// GET api/actions
public object Get()
{
//New up a strongly typed object if you want to return a specific type
//and change Action return type accordingly
var testObjet = new (){
Name= "Test name",
Description= "Test Description"
};
return testObjet;
}
Dan has posted a similar answer below so let me try to address your other problem. To serialize the enum, I would suggest you hide it in a public string property which would return the string value of the enum,
public class DataObject{
public MyEnum SomeEnumValue;
public string EnumValue{
get {
//..return SomeEnumValue string value
}
}
}
You can then read the value from EnumValue which should be properly serialized as you want.

How to return serialized to JSON using C#

Im working with a WCF in which i return JSON. But i get messages looking like
"{\"ids\":[\"id\":1,\"id\":34,\"id\":67,\"id\":100,\"id\":133,\"id\":166,\"id\":199]}"
How do I get rid of the first and last qoutation marks?
EDIT:
public class Ids {
public IdDetails[] ids{get;set}
}
public class IdDetails{
public int id {get;set}
}
And here I return JSON
public string GetIds(){
Ids ids = new Ids();
List<IdDetails> idd = new List<IdDetails>();
for(int i=0;i<10; i++){
idd.add(new IdDetails(i+1*33));
}
ids.ids = idd.ToArray();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
string json = jSerialize.Serialize(ids);
return ids;
}
*EDIT 2: SOLVED *
The method shouldn't return a string. It should return a Ids-object. No need to serialize.
Set the ResponseFormat = WebMassageFormat.Json and it will work.
Thanks anyways!
Are you looking with the Visual Studio Debugger at the string?
The debugger shows strings as C# string literal. The string itself doesn't actually contain the leading and trailing " characters and the \ characters.
Console.WriteLine(s);
Output:
{"ids":["id":1,"id":34,"id":67,"id":100,"id":133,"id":166,"id":199]}
JavaScriptSerializer Class
The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.
I've used it in non-web applications.

Categories

Resources