Related
I want many of them but I don't how to make so many I can only make one just like this here:
[
{
"NAME1": "Max1"
}
]
But I want to make this:
[
{
"NAME1": "Max1"
},
{
"NAME2": "Max2"
},
{
"NAME3": "Max3"
},
{
"NAME4": "Max4"
}
]
How do I do it
Here is my code:
public void nxt_Click(object sender, EventArgs e)
{
List<Voc> _data = new List<Voc>();
_data.Add(new Voc()
{
NAME = textBox1.Text
});
string jger2 = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);
File.WriteAllText(#"D:\Users\Oxygen\Desktop\ss.json", jger2);
}
public class Voc
{
public string NAME { get; set; }
}
has anybody any ideas?
Below are a couple of ways to do this, demonstrated in this fiddle.
The first uses anonymous types, which are objects which don't have a real class, but are constructed by assigning values to properties. However, to use these you need to know the property names at compile time; so this will only work if you know exactly how many names you'll have in your array. e.g.
var data = new object[] {
new {Name1 = textBox1.Text}
,new {Name2 = textBox2.Text}
,new {Name3 = textBox3.Text}
,new {Name4 = textBox4.Text}
};
Another approach is to use a dictionary, which can be populated with name value pairs at runtime, then you can convert these to JSON. E.g.
var textBoxes = new [] {textBox1, textBox2, textBox3, textBox4};
var dict = new Dictionary<string,string>();
for (var i = 0; i< textBoxes.Length; i++)
{
dict.Add(string.Format("Name{0}", i), textBoxes[i].Text );
}
However
I would strongly advise against these methods; or rather this approach. JSON is designed to be made up of key-value pairs. They keys should be known, whilst the values can change. That means that if you have 4 different values for a name instead of holding 4 different names, you hold those values against that name; e.g.
{"Name": ["Max1","Max2","Max3","Max4"]}
...with the number of the element being defined by the array's index.
The C# for that looks like this:
SomeClass data = GetValues();
//...
public class SomeClass
{
public IEnumerable<string> Name {get;private set;}
//or: public string[] Name {get;private set;}
//...
}
If you really need to store the different names, those should be stored as values against the name key; e.g.
[
{"Name": "Name1", "Value": "Max1"}
,{"Name": "Name2", "Value": "Max2"}
,{"Name": "Name3", "Value": "Max3"}
,{"Name": "Name4", "Value": "Max4"}
]
The C# for that looks like this:
IEnumerable<SomeClass> data = GetValues();
//or: SomeClass[] data = GetValues();
//...
public class SomeClass
{
public string Name {get;private set;}
public string Value {get;private set;}
//...
}
Full Code
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
//setup our test data
var textBox1 = new TextBox("Max1");
var textBox2 = new TextBox("Max2");
var textBox3 = new TextBox("Max3");
var textBox4 = new TextBox("Max4");
//demo using anonymous objects (NB: property names must be known at compile time)
var data = new object[] {
new {Name1 = textBox1.Text}
,new {Name2 = textBox2.Text}
,new {Name3 = textBox3.Text}
,new {Name4 = textBox4.Text}
};
Console.WriteLine( JsonConvert.SerializeObject(data, Formatting.Indented));
//demo using a dictionary
var textBoxes = new [] {textBox1, textBox2, textBox3, textBox4};
var dict = new Dictionary<string,string>();
for (var i = 0; i< textBoxes.Length; i++)
{
dict.Add(string.Format("Name{0}", i+1), textBoxes[i].Text );
}
Console.WriteLine("[" + string.Join(",", dict.Select( e => string.Format("{{\"{0}\": \"{1}\"}}", e.Key.Replace("\"","\"\""), e.Value.Replace("\"","\"\"") ) )) + "]"); //based on https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c/5597628#5597628
}
}
//dummy class
public class TextBox
{
public TextBox(string text){Text = text;}
public string Text{get;private set;}
}
First of all, your Array is poorly formatted.
It should be:
{
"NAMES": [
{
"NAME": "Max1"
},
{
"NAME": "Max2"
},
{
"NAME": "Max3"
},
{
"NAME": "Max4"
}
]
}
Run that through json2Csharp.com and it will generate the following:
public class NAME
{
public string NAME { get; set; }
}
public class RootObject //Rename this
{
public List<NAME> NAMES { get; set; }
}
Which you should be able to serialize and deserialize using almost any C# JSON library.
My Web API (code that generates JSON) is generating the following JSON string. It seems, if I am not wrong, that it has been encoded twice:
"\"[{\\\"SportID\\\":1,\\\"SportName\\\":\"Tennis\\\"},{\"SportID\\\":2,\\\"SportName\\\":\\\"Footbal\\\"},{\"SportID\\\":3,\"SportName\":\\\"Swimming\\\"}]\""
Web API code:
public string JSONTest()
{
List<Sport> sports = new List<Sport>();
sports.Add(new Sport() { SportID = 1, SportName = "Tennis" });
sports.Add(new Sport() { SportID = 2, SportName = "Footbal" });
sports.Add(new Sport() { SportID = 3, SportName = "Swimming" });
try
{
return JsonConvert.SerializeObject(sports);
}
catch (Exception ex) { }
}
Sport class:
public class Sport { public int SportID { get; set; } public string SportName { get; set; } }
Screenshot of getting JSON:
The following line gives me an error, I think because of twice encoding:
var JavaScriptSerializerResult = (new JavaScriptSerializer()).Deserialize< List<Sport>>(jsonResponse);
I get the same error if try with this:
var jsonConvertResult = JsonConvert.DeserializeObject<List<Sport>>(jsonResponse);
How can I fix my Web API to not encode twice, or if that is not the problem, how can I decode this JSON?
I think you should try JsonConvert.DeserializeObject to deserialize the JSON:
public class Sport
{
// Dummy "Sport" class as it was not mentioned by OP.
public int SportID { get; set; }
public string SportName { get; set; }
}
I get serialized JSON as:
Deserialized it:
string json = JSONTest();
var obj = JsonConvert.DeserializeObject<List<Sport>>(json);
Output:
UPDATE:
As per OP's shared JSON (which is being received from server), encoding can be removed by using:
private string RemoveEncoding(string encodedJson)
{
var sb = new StringBuilder(encodedJson);
sb.Replace("\\", string.Empty);
sb.Replace("\"[", "[");
sb.Replace("]\"", "]");
return sb.ToString();
}
Deserialize it by:
string js = "\"[{\\\"SportID\\\":1,\\\"SportName\\\":\"Tennis\\\"},{\"SportID\\\":2,\\\"SportName\\\":\\\"Footbal\\\"},{\"SportID\\\":3,\"SportName\":\\\"Swimming\\\"}]\"";
string res = RemoveEncoding(js);
var obj = JsonConvert.DeserializeObject<List<Sport>>(res);
Shorter sample for json.net library.
Here, entity is my serializable C# object. I use JsonConvert along with some formatting and specify to ignore reference looping to prevent circular referencing.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject (entity, Formatting.Indented,
new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
});
Use Linq Query Concept:
public string JSONTest()
{ List<Sport> sports = new List<Sport>();
sports.Add(new Sport() { SportID = 1, SportName = "Tennis" });
sports.Add(new Sport() { SportID = 2, SportName = "Footbal" });
sports.Add(new Sport() { SportID = 3, SportName = "Swimming" });
var result_sports = (from row in sports
group row by new { row.SportID , row.SportName} into hdr
select new Sport()
{
SportID = hdr.Key.SportID ,
SportName = hdr.Key.SportName ,
}).ToList();
string jsondata = new JavaScriptSerializer().Serialize(result_sports);
}
Summary: Your return object is being serialized twice. Remove your hand-rolled serialization code and return objects from your web services - not JSON strings.
Your JSON is indeed being serialized 'twice'. Look closely at this screenshot and we see escaped quote marks:
Your list properly serialized should produce a JSON string something like this:
[{"SportID":1,"SportName":"Tennis"},{"SportID":2,"SportName":"Footbal"},{"SportID":3,"SportName":"Swimming"}]
But we have something more like this:
"[{\"SportID\":1,\"SportName\":\"Tennis\"},{\"SportID\":2,\"SportName\":\"Footbal\"},{\"SportID\":3,\"SportName\":\"Swimming\"}]"
I can replicate this (code below) and it means that your JSON string has itself been fed through a serializer.
This is almost certainly due to you manually serializing your List<Sport>. You don't need to do that. Web API serializes for you - hence the second run through a serializer.
Change the return type of your Web API function if necessary, and then instead of writing:
return JsonConvert.SerializeObject(sports);
just do
return sports;
Web API will take care of the serialization and you will no longer have the bothersome quotes and escape characters.
Code dump I tested with:
void Main()
{
string json = JSONTest();
Console.WriteLine(json);
var obj = JsonConvert.DeserializeObject<List<Sport>>(json);
string jsonX2 = JsonConvert.SerializeObject(json);
Console.WriteLine(jsonX2);
obj = JsonConvert.DeserializeObject<List<Sport>>(jsonX2); // exception
}
public string JSONTest()
{
List<Sport> sports = new List<Sport>();
sports.Add(new Sport() { SportID = 1, SportName = "Tennis" });
sports.Add(new Sport() { SportID = 2, SportName = "Footbal" });
sports.Add(new Sport() { SportID = 3, SportName = "Swimming" });
return JsonConvert.SerializeObject(sports);
}
public class Sport
{
public int SportID { get; set; }
public string SportName { get; set; }
}
Is it possible to form an object from two classes and then serialize it to JSON, and when deserialize it back be able to get those two objects.
say I have: an object of Student and a List<Course>
is it possible to combine these two objects in one JSON object.
I need this because building up a class for every JSON object would be very exhausting in the project I'm working on!
Is it possible to form an object from two classes and then serialize it to JSON
Yes it is possible to do this just use Merge from JObject
for example here is an example
class Student
{
public string Name { get; set; }
}
class Course
{
public string Title { get; set; }
}
var std = new Student() {Name = "foo"};
var lstCours = new List<Course>() { new Course(){Title = "math"}};
var stdJson = JsonConvert.SerializeObject(new {student=std});
var lstCoursJson = JsonConvert.SerializeObject( new{Cours= lstCours});
JObject jObjectStd = JObject.Parse(stdJson);
JObject jObjectLstCours = JObject.Parse(lstCoursJson);
jObjectStd.Merge(jObjectLstCours,new JsonMergeSettings(){MergeArrayHandling = MergeArrayHandling.Concat});
Console.WriteLine(jObjectStd.ToString());
here what you get as a merge
{
"student": {
"Name": "foo"
},
"Cours": [
{
"Title": "math"
}
]
}
to deserialize this is pretty simple with JSON.net
var stdParsed = JObject.Parse(json).Property("student").Value.ToString();
var lstCoursParsed = JObject.Parse(json).Property("Cours").Value.ToString();
var stdDes = JsonConvert.DeserializeObject<Student>(stdParsed);
var lstCoursDes = JsonConvert.DeserializeObject<List<Course>>(lstCoursParsed);
Yes, this is possible, and is actually very straightforward to do.
Say you have your two objects like this:
var student = new Student { Name = "Joe Schmoe" };
var courses = new List<Course>
{
new Course { Title = "Underwater Basket Weaving 101" },
new Course { Title = "History of Pancakes 102" }
};
On the serializing side, just use an anonymous object to combine your objects together and then serialize that:
var anon = new { Student = student, Courses = courses };
var json = JsonConvert.SerializeObject(anon, Formatting.Indented);
Here is the JSON you would get:
{
"Student": {
"Name": "Joe Schmoe"
},
"Courses": [
{
"Title": "Underwater Basket Weaving 101"
},
{
"Title": "History of Pancakes 102"
}
]
}
You can combine as many objects together as you need to in this way.
On the flip side, you can deserialize to a dynamic variable (which is a JObject behind the scenes) and then recreate your original strongly-typed objects from it using ToObject<T>().
dynamic obj = JsonConvert.DeserializeObject(json);
var student = obj.Student.ToObject<Student>();
var courses = obj.Courses.ToObject<List<Course>>();
Round-trip demo: https://dotnetfiddle.net/OKJBg2
Alternatively you can use deserialize-by-example to deserialize back to an anonymous object if you don't like the dynamic variable / JObject idea. To do that, you first create an empty anonymous object in the same shape as the JSON to use as a "template" and then pass it along with the JSON to JsonConvert.DeserializeAnonymousType:
var template = new { Student = new Student(), Courses = new List<Course>() };
var anon = JsonConvert.DeserializeAnonymousType(json, template);
Student student = anon.Student;
List<Course> courses = anon.Courses;
Demo: https://dotnetfiddle.net/Inz0r8
Serialize a KeyValuePair<Student, List<Course>> and deserialize to the KeyValuePair again.
var student = ...;
var courses = ...;
var json = JsonConvert.SerializeObject(new KeyValuePair<Student, List<Course>>(student, courses));
Then, deserialize it this way:
var pair = JsonConvert.DeserializeObject<KeyValuePair<Student, List<Course>>>(json);
var student = pair.Key;
var courses = pair.Value;
This is a workaround, but it's easy to understand, and very easy to use (compared to JObject or a class to combine them).
Just Create new Class which has those 2 objects like this
public class StudentWithCours
{
public Student student { get; set; }
public List<Course> course { get; set; }
}
after that you can serialize/deserialize the class exemplar like this
.......
StudentWithCours myObject = new StudentWithCours();
//your some logic here]
var serilizedObject = JsonConvert.SerializeObject(myObject);
var deserilizedObject = JsonConvert.DeserializeObject<StudentWithCours>(serilizedObject);
It is. This one-liner depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
var myObject = ...;
Newtonsoft.Json.JsonConvert.SerializeObject(myObject);
Documentation: Serializing and Deserializing JSON
Other possibility:
You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
Other options are available here, where you can find above two answers, along with many others.
Piece of code:
public class Student
{
public string Name { get; set; }
public List<Course> Courses { get; set; } = new List<Course>();
public class Course
{
public string Name { get; set; }
public string Code { get; set; }
}
}
var student = new Student
{
Name = "Jack",
Courses = new List<Student.Course>
{
new Student.Course() {Name = "MATH", Code = "MA"},
new Student.Course() {Name = "Science", Code = "SC"}
}
};
var str = JsonConvert.SerializeObject(student);
var studentDeserialized = JsonConvert.DeserializeObject<Student>(str);
Try it out for yourself
I am using this method to form json string and this is working fine. But i can't handle this if it contains more properties. Is there any other better method than this?
string.Format("{0}{1}longUrl{1}:{1}{2}{1}{3}", "{", "\"", longUrl,"}");
The output is
{"longUrl":"http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"}
Well, a "better" way of doing this would be to use a Json library. If this is in the context of an Asp.Net website (in the latter versions), there is the Json.Net library that is automatically referenced. If not, you can use Nuget to add a reference to your project or manually add it, whichever your prefer. You could then do:
JsonConvert.SerializeObject(new { longUrl = longUrl });
Note that you can also just use new { longUrl } and the property name will be the same as your variable name.
You can use JSON.Net library. You can create an entity class which you want to covert to JSON rather than using string formatter.
for e.g.
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
Account account = new Account
{
Email = "james#example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
Console.WriteLine(json);
output:
// {
// "Email": "james#example.com",
// "Active": true,
// "CreatedDate": "2013-01-20T00:00:00Z",
// "Roles": [
// "User",
// "Admin"
// ]
// }
You could just use a JSON serializer such as JSON.NET. Failing that, you can simplify somewhat:
string.Format(#"{{""longUrl"":""{0}""}}", longUrl);
You may use Newtonsoft.Json:
using System.Text;
using Newtonsoft.Json;
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
var d = new
{
longUrl = "http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72",
someOtherProeprty = 1
};
var s = new JsonSerializer();
var sb = new StringBuilder();
using (var w = new StringWriter(sb))
{
s.Serialize(w, d);
}
Console.WriteLine(sb.ToString());
}
}
you can using System.Web.Script.Serialization;
then do
var dict = new Dictionary<string, string>
{
{"longUrl","http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"},
{"anotherUrl", "another Url"}
};
var serializer = new JavaScriptSerializer();
serializer.Serialize(dict);
As an example to create the following JSON string
{
"userId" : "121211-121112",
"accountId": "xhd1121-kdkdj11"
}
use the following string interpolation and formating.
var jsonString = $#"{{
"userId"": ""{user.Id},""
""accountId"": ""{account.Id}""
}}"';
How can I convert the following JSON response to a C# object?
{
"err_code": "0",
"org": "CGK",
"des": "SIN",
"flight_date": "20120719",
"schedule": [
["W2-888","20120719","20120719","1200","1600","03h00m","737-200","0",[["K","9"],["F","9"],["L","9"],["M","9"],["N","9"],["P","9"],["C","9"],["O","9"]]],
["W2-999","20120719","20120719","1800","2000","01h00m","MD-83","0",[["K","9"],["L","9"],["M","9"],["N","9"]]]
]
}
To create a class off a json string, copy the string.
In Visual Studio, in the menu at the top, click Edit > Paste special > Paste Json as classes.
Install Newtonsoft.Json via Nuget
Paste the following code into your project, "jsonString" being the variable you want to deserialize :
Rootobject r = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonString);
Don't forget to rename Rootobject to be more descriptive eg ILoveTheSmellOfNapalmInTheMorning-that was a joke
First create a class to represent your json data.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer classe's instance. Your class should looks similar to the JSON structure (Properties)
I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
Serialization Example:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Performance Comparison To Other JSON serializiation Techniques
copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,
A cs class will be generated use that cs file as below:
var generatedcsResponce = JsonConvert.DeserializeObject<RootObject>(yourJson);
where RootObject is the name of the generated cs file;
This will take a json string and turn it into any class you specify
public static T ConvertJsonToClass<T>(this string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
class Program
{
static void Main(string[] args)
{
var res = Json; //Json that has to be converted
Response resp = new Response();
resp = JsonSerializer.Deserialize<Response>(res);
Console.WriteLine(res);
}
}
public class Response
{
public bool isValidUser { get; set; }
public string message { get; set; }
public int resultKey { get; set; }
}