JSON C# .NET Compile Class Name [duplicate] - c#

This question already has answers here:
Json.NET serialize object with root name
(10 answers)
Closed 8 years ago.
I am working on a C# project however I am in need of some advice.
I am presently posting to my site:
{Tags : 'App', Limit : '10' }
And it can cast this to the following class
[Serializable]
public class MiloFilter
{
public string Tags { get; set; }
public string Limit { get; set; }
}
However what I am wanting to accomplish is that I would like to post my JSON like this:
{ MiloFilter : {Tags : 'SomeTag', Limit : '1' }}
However when I try and parse it using the following method it fails.
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var miloFilter = js.Deserialize<MiloFilter>(bodyText);
How can I acomplish this?

You can easily create your own serializer
var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);
string Serialize<T>(T o)
{
var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;
var jv = JValue.FromObject(o);
return new JObject(new JProperty(attr.Title, jv)).ToString();
}
source

Related

Avoid re-serializing of a json string [duplicate]

This question already has answers here:
Is there an equivalent for JRaw in System.Text.Json
(1 answer)
How can I serialize a literal JSON value with System.Text.Json?
(1 answer)
Closed 5 months ago.
Is there a way to selectively exclude a field from re-serialization, if it already contains a valid json string?
Here is what I am attempting.
First, I define a class of the result row I recieve from my database.
public class objectToSerialize
{
public string identifier { get; set; }
public string jsonPayload { get; set; }
public objectToSerialize()
{
identifier = String.Empty;
jsonPayload = String.Empty;
}
}
Then I run my query and add all the results to a list.
List<objectToSerialize> listOfobjectToSerialize = new List<objectToSerialize>();
[...]
while(SqlDataReader.Read())
{
[...]
listOfobjectToSerialize.add(objectToSerialize)
}
Finally, I return my list as an APS.NET OkObjectResult, which serializes the list to JSON by default.
[...]
return (ActionResult)new OkObjectResult(listOfobjectToSerialize);
The jsonPayload already contains a json string, that should not be re-serialized again when returning the result.
So far I have deserialized the jsonPayload to an object, which was then serialized fine, but I would like to avoid that unnessesary step.
I have tried using the field attributes [JsonIgnore] and [NonSerialized()] but they remove the field from the result altogether.
Is there a way to include the jsonPayload string as-is?
Here is an example:
objectToSerialize.identifier = 123;
objectToSerialize.jsonPayload = #"
{
"ThisIsAKey" : "ThisIsAValue"
}"
Desired output:
{
"identifier" : 123,
"jsonPayload" : {
"ThisIsAKey" : "ThisIsAValue"
}
}
Actual output:
{
"identifier" : 123,
"jsonPayload" : "{
\"ThisIsAKey\" : \"ThisIsAValue\"
}"
}
So far I am trying to write my own custom JsonConverter.
this will not be even compiled
objectToSerialize.jsonPayload = #"
{
"ThisIsAKey" : "ThisIsAValue"
}"
if you want Desired output
objectToSerialize.jsonPayload = new
{
ThisIsAKey = "ThisIsAValue"
};
but as I guess your jsonPayload is a string , so you can only do this
objectToSerialize.jsonPayload = #"{
""ThisIsAKey"" : ""ThisIsAValue""
}";
leave like this, otherwise you are just looking for a trouble, you will not be able to deserialize jsonPayload to string when you get your response.
If it is already the JSON, we could give a try to plain/text as the content type of the response.
May be,
Request.Content = "text/plain";
return Content(alreadyCreatedJson);

How to deserialize JSON object using constructor into itself in C#? [duplicate]

This question already has answers here:
Overlay data from JSON string to existing object instance
(4 answers)
Closed 4 years ago.
I want to create a new object, and during object creation make an RPC call to get properties for it, and then return the object populated with the properties. See this example:
using Newtonsoft.Json;
class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(int Id)
{
// here would be an RPC call to get the FirstName,LastName. result is JSON
string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
this = JsonConvert.DeserializeObject<Person>(result);
}
}
class Program
{
static void Main(string[] args)
{
var p = new Person(1);
// p.FirstName should be Bob
}
}
I don't know how to do this in the constructor without getting a StackOverflow Exception.
One option to consider is to use a static method inside Person:
public static Person GetPerson(int Id)
{
// here would be an RPC call to get the FirstName,LastName. result is JSON
string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
return JsonConvert.DeserializeObject<Person>(result);
}
This avoids the recursive nature of your original code.
Another option is to change the class to a struct. structs allow you to assign to this (unlike classes). And they have a default constructor (separate to your one taking a parameter) so that there is no recursive behaviour.

Why does Newtonsoft.Json not serialise this property? [duplicate]

This question already has answers here:
How do I get json.net to serialize members of a class deriving from List<T>?
(3 answers)
Closed 5 years ago.
Consider the following program: (.NET Fiddle Link)
public class Program
{
public static void Main()
{
var carsa = new ListOfCarsA();
carsa.Cars.Add("Toyota");
carsa.Cars.Add("Lexus");
Console.WriteLine(JsonConvert.SerializeObject(carsa, Formatting.Indented));
var carsb = new ListOfCarsB();
carsb.Add("Nissan");
carsb.Add("Infiniti");
Console.WriteLine(JsonConvert.SerializeObject(carsb, Formatting.Indented));
}
}
public class ListOfCarsA
{
public string CollectionName { get { return "CarsA"; } }
public List<string> Cars { get; set; }
public ListOfCarsA()
{
Cars = new List<string>();
}
}
public class ListOfCarsB : List<string>
{
public string CollectionName { get { return "CarsB"; } }
}
This then outputs the following:
{
"CollectionName": "CarsA",
"Cars": [
"Toyota",
"Lexus"
]
}
And
[
"Nissan",
"Infiniti"
]
Why does the property CollectionName not get serialised and output CarsB, but the same property on the ListOfCarsA results in CarsA being serialised?
What is the solution to this problem - How could I have a class similar to ListOfCarsB but still have any extra members serialised? I have tried using the attributes [JsonProperty("CollectionName"] and [JsonRequired] but these seem to do nothing.
This is because your second example IS a list, whilst the first example only contains one. Json.Net knows how to create json from lists and so is ignoring the rest of your custom code. Not much you can do about this except write a custom formatter

.NET classes needed to deserialize JSON string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in C#
I'm trying to deserialize a JSON string from the openlibrary.org in an ASP.NET (4.5) web application using JSON.NET.
My aim is to be able to read the 5 properties below from a single .Net object.
The example JSON
I have is:
{"ISBN:0201558025":
{
"bib_key": "ISBN:0201558025",
"preview": "noview",
"thumbnail_url": "http://covers.openlibrary.org/b/id/135182-S.jpg",
"preview_url": "http://openlibrary.org/books/OL1429049M/Concrete_mathematics",
"info_url": "http://openlibrary.org/books/OL1429049M/Concrete_mathematics"
}
}
I can get it to work fine without the first line, but I'm a bit lost trying to work out how I should structure my classes.
I'm new to JSON and haven't played with C#/VB.NET in a few years so getting very lost.
Update
I have the following code:
Dim url = "http://openlibrary.org/api/books?bibkeys=ISBN:0201558025&format=json"
Dim webClient = New System.Net.WebClient
Dim json = webClient.DownloadString(url)
Dim book As Book = JsonConvert.DeserializeObject(Of Book)(json)
And the class Book:
Public Class Book
Public bib_key As String
Public preview As String
Public preview_url As String
Public info_url As String
End Class
However, book turns up empty.
There is a website called json2csharp - generate c# classes from json:
public class RootObject
{
public string bib_key { get; set; }
public string preview { get; set; }
public string thumbnail_url { get; set; }
public string preview_url { get; set; }
public string info_url { get; set; }
}
The json format is a little off, remove the {"ISBN:0201558025": since you have the ISBN as the bib_key
Try using JSON.Net
or
JavaScriptSerializer Class
or
DataContractSerializer class
I think it can be deserialized as a Dictionary.
new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, BookInfoClass>>(jsonString);

Getting nested data out of JSON in C#

I have some JSON with Two objects and these each have 3 objects nested.
{
"FirstPerson": {
"number": "101",
"a10": "1001",
"a20": "1002"
},
"SecondPerson": {
"number": "102",
"a10": "2001",
"a20": "2001"
}
}
In c# asp.net mvc2 I've been able to get to "FirstPerson" or "SecondPerson" using a Hashtable but how do I get to "number" or "a10" when I know "FirstPerson"?
e.g. an objects inside an object.
Is a Hashtable the best use for this or should I be using something else?
Thanks in advance.
I found that solution for your problem may be give a clue to solve that
Want to convert a C# object into it's JSON equivalent? Here is a simple object from the System.Web.Script namespace that does exactly that:
System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)
Using this object we serialize and deserialize objects in C#. Here is a quick sample:
A simple Employee object:
public class Employee
{
public string Name { get; set; }
public string Age { get; set; }
public string ID { get; set; }
}
Adding some instances of them to a List:
Employee oEmployee1 =
new Employee{Name="Pini",ID="111", Age="30"};
Employee oEmployee2 =
new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
Employee oEmployee3 =
new Employee { Name = "Yoni", ID = "Biton", Age = "20" };
List oList = new List()
{ oEmployee1, oEmployee2, oEmployee3 };
Serializing then:
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
And here is the output:
[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]
For your consideration here is the link http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx
I have had good results using JsonConvert. It seems to do a good job of knowing what to do with collections. Just define the class you want to de-serialize to and have at it.
http://james.newtonking.com/projects/json-net.aspx
Example:
MyCollection col = JsonConvert.DeserializeObject<MyCollection>(this.HttpContext.Request.Params[0]);
Where MyCollection is a class which contains a collection of, in your case, people.
You could assign the JSON object to a dynamic variable and access the properties that way (only in C# 4.0 though)
dynamic jsonData = jsonObject;
int workflowNum = jsonData.SecondPerson[0].workflow;

Categories