Me gusta cargando with con C#
Estoy tratando de deserializar una llamada a la API de Facebook friends graph en una lista de objetos. El objeto JSON se ve así:
{"data":[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"},
{"id":"532652067","name"...
List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
No funciona porque el objeto primitivo no es válido.
¿Cómo puedo deserializar esto?
6 answers
Necesitas crear una estructura como esta:
public class Friends
{
public List<FacebookFriend> data {get;set;}
}
public class FacebookFriend
{
public string id {get;set;}
public string name {get;set;}
}
Entonces usted debe ser capaz de hacer:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
Los nombres de mis clases son solo un ejemplo. Deberías usar nombres propios.
Adición de prueba de muestra:
string json=
@"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}",item.id,item.name);
}
Produce:
id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-10 13:28:22
A Veces Prefiero Los objetos Dinámicos
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string.
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values.
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id,
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-01 14:40:26
Muy fácilmente podemos analizar json con la ayuda de dictionary y JavaScriptSerializer. aquí está el código de ejemplo por el cual analizo json del archivo ashx.
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Name = sData["Name"].ToString();
string _Subject = sData["Subject"].ToString();
string _Email = sData["Email"].ToString();
string _Details = sData["Details"].ToString();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-01 14:43:21
Una gran manera de generar automáticamente estas clases para usted es copiar su salida JSON y lanzarlo aquí:
Le proporcionará un punto de partida para retocar sus clases para la deserialización.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-17 22:05:50
Estoy de acuerdo con Ícaro (habría comentado si pudiera), pero en lugar de usar una clase CustomObject , Usaría un Diccionario (en caso de que facebook agregue algo).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
O
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-21 14:44:10
Newtonsoft.JSON
es una buena solución para este tipo de situaciones. También Newtonsof.JSON
es más rápido que otros como JavaScriptSerializer
, DataContractJsonSerializer
.
En este ejemplo, puede lo siguiente:
var jsonData = JObject.Parse("your json data here");
Luego puede convertir jsonData a JArray
y puede usar for loop para obtener datos en cada iteración.
Además, quiero añadir algo.
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Trabajar con objetos dinámicos y usar Newtonsoft serialize es una buena opción.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-02 07:36:53