Jak przekonwertować obiekt JSON na niestandardowy obiekt C#?
Czy istnieje łatwy sposób na wypełnienie mojego obiektu C# obiektem JSON przekazanym przez AJAX?
/ / jest to obiekt JSON przekazany do C # WEBMETHOD ze strony używającej JSON.stringify
{
"user": {
"name": "asdf",
"teamname": "b",
"email": "c",
"players": ["1", "2"]
}
}
/ / C # WebMetod odbierający obiekt JSON
[WebMethod]
public static void SaveTeam(Object user)
{
}
/ / Klasa C # reprezentująca strukturę obiektu JSON przekazaną do WebMethod
public class User
{
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
13 answers
Dobrym sposobem na użycie JSON w C# jest JSON.NET
Quick Starts & API Documentation from JSON.NET -Oficjalna strona pomóc w pracy z nim.
Przykład użycia:
public class User
{
public User(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run()
{
string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-15 21:35:55
Ponieważ wszyscy kochamy jeden kod
Newtonsoft jest szybszy niż java script serializer. ... ten zależy od pakietu Newtonsoft NuGet, który jest popularny i lepszy niż domyślny serializer.
Jeśli mamy klasę To użyj poniżej.
Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(Json Object);
No class then use dynamic
var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Json Object);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-21 07:35:58
Aby zachować otwarte opcje, jeśli używasz. NET 3.5 lub nowszego, oto zawinięty przykład, którego możesz użyć bezpośrednio z frameworka używając Generics. Jak już wspominali inni, jeśli nie są to tylko proste przedmioty, powinieneś naprawdę używać JSON.net.
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
Będziesz potrzebował:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-21 20:41:20
Biorąc pod uwagę próbkę kodu, nie powinieneś robić nic innego.
Jeśli przekażesz łańcuch JSON do swojej metody web, automatycznie przetworzy on łańcuch JSON i utworzy wypełniony obiekt użytkownika jako parametr dla Twojej metody SaveTeam.
Ogólnie jednak, można użyć klasy JavascriptSerializer
Jak poniżej, lub dla większej elastyczności, użyć dowolnego z różnych frameworków Json tam (Jayrock JSON jest dobry) dla łatwej manipulacji JSON.
JavaScriptSerializer jss= new JavaScriptSerializer();
User user = jss.Deserialize<User>(jsonResponse);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-11 18:38:11
Innym bardzo prostym rozwiązaniem jest użycie biblioteki Newtonsoft.Json:
User user = JsonConvert.DeserializeObject<User>(jsonString);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-19 22:29:45
Poniższe 2 Przykłady wykorzystują albo
- JavaScriptSerializer w systemie .Www.Scenariusz.Serializacja Lub
- Json.Dekodować Pod systemem.Www.Helpers
Przykład 1: używanie systemu.Www.Scenariusz.Serializacja
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void Test()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
dynamic x = jsonObject["user"]; // result is Dictionary<string,object> user with fields name, teamname, email and players with their values
x = jsonObject["user"]["name"]; // result is asdf
x = jsonObject["user"]["players"]; // result is object[] players with its values
}
}
}
Użycie: obiekt JSON do niestandardowego obiektu C#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
using System.Linq;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void TestJavaScriptSerializer()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
}
public class User {
public User(string json) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<dynamic>(json);
name = (string)jsonObject["user"]["name"];
teamname = (string)jsonObject["user"]["teamname"];
email = (string)jsonObject["user"]["email"];
players = jsonObject["user"]["players"];
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
}
Przykład 2: używanie systemu.Www.Helpers
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void TestJsonDecode()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
dynamic jsonObject = Json.Decode(json);
dynamic x = jsonObject.user; // result is dynamic json object user with fields name, teamname, email and players with their values
x = jsonObject.user.name; // result is asdf
x = jsonObject.user.players; // result is dynamic json array players with its values
}
}
}
Użycie: JSON object to Custom C # object
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;
using System.Linq;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void TestJsonDecode()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
}
public class User {
public User(string json) {
var jsonObject = Json.Decode(json);
name = (string)jsonObject.user.name;
teamname = (string)jsonObject.user.teamname;
email = (string)jsonObject.user.email;
players = (DynamicJsonArray) jsonObject.user.players;
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
}
Ten kod wymaga dodania systemu.Www.Helpers namespace found in,
%ProgramFiles% \ Microsoft ASP.NET\ASP.NET www Pages{VERSION}\Assemblies\System.Www.Pomocnicy.dll
Lub
Mam nadzieję, że to pomoże!%ProgramFiles (x86) % \ Microsoft ASP.NET\ASP.NET www Pages{VERSION}\Assemblies\System.Www.Pomocnicy.dll
public static class Utilities
{
public static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
Więcej informacji można znaleźć pod poniższym linkiem http://ishareidea.blogspot.in/2012/05/json-conversion.html
O DataContractJsonSerializer Class
możesz przeczytać TUTAJ .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-16 16:42:39
Korzystanie z JavaScriptSerializer () jest mniej rygorystyczne niż oferowane ogólne rozwiązanie : public static T Deserialize (string json)
To może się przydać przy przekazywaniu json do serwera, który nie pasuje dokładnie do definicji obiektu, na który próbujesz przekonwertować.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-14 17:56:46
Pod względem wydajności, znalazłem serializer ServiceStack ' a nieco szybciej niż inne. To klasa JsonSerializer w ServiceStack.Przestrzeń nazw tekstowych.
Https://github.com/ServiceStack/ServiceStack.Text
ServiceStack jest dostępny w pakiecie NuGet: https://www.nuget.org/packages/ServiceStack/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-17 07:19:17
JSON.Net jest najlepszym rozwiązaniem, ale w zależności od kształtu obiektów i czy istnieją okrągłe zależności, można użyć JavaScriptSerializer lub DataContractSerializer.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-11 18:38:36
Generator klas JSON c# na codeplex generuje klasy, które dobrze współpracują z NewtonSoftJS.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-25 16:45:37
JavaScript Serializer: requires using System.Web.Script.Serialization;
public class JavaScriptSerializerDeSerializer<T>
{
private readonly JavaScriptSerializer serializer;
public JavaScriptSerializerDeSerializer()
{
this.serializer = new JavaScriptSerializer();
}
public string Serialize(T t)
{
return this.serializer.Serialize(t);
}
public T Deseralize(string stringObject)
{
return this.serializer.Deserialize<T>(stringObject);
}
}
Data Contract Serializer: requires using System.Runtime.Serialization.Json;
- Typ ogólny T powinien być serializowalny więcej o umowie danych
public class JsonSerializerDeserializer<T> where T : class
{
private readonly DataContractJsonSerializer jsonSerializer;
public JsonSerializerDeserializer()
{
this.jsonSerializer = new DataContractJsonSerializer(typeof(T));
}
public string Serialize(T t)
{
using (var memoryStream = new MemoryStream())
{
this.jsonSerializer.WriteObject(memoryStream, t);
memoryStream.Position = 0;
using (var sr = new StreamReader(memoryStream))
{
return sr.ReadToEnd();
}
}
}
public T Deserialize(string objectString)
{
using (var ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes((objectString))))
{
return (T)this.jsonSerializer.ReadObject(ms);
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-28 09:17:14
Zamiast wysyłać jako obiekt .
Utwórz publiczną klasę właściwości, która jest dostępna i wyślij dane do Webmethod.
[WebMethod]
public static void SaveTeam(useSomeClassHere user)
{
}
Używaj tych samych nazw parametrów w wywołaniu ajax do wysyłania danych.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-20 12:47:13