Deserialize Json Array Newtonsoft.Json - json

I have the following JSON
[
{
"id":"656332",
"t":"INTU",
"e":"NASDAQ",
"l":"108.35",
"l_fix":"108.35",
"l_cur":"108.35",
"s":"2",
"ltt":"4:00PM EST",
"lt":"Nov 8, 4:00PM EST",
"lt_dts":"2016-11-08T16:00:01Z",
"c":"+0.45",
"c_fix":"0.45",
"cp":"0.42",
"cp_fix":"0.42",
"ccol":"chg",
"pcls_fix":"107.9",
"el":"108.43",
"el_fix":"108.43",
"el_cur":"108.43",
"elt":"Nov 8, 4:15PM EST",
"ec":"+0.08",
"ec_fix":"0.08",
"ecp":"0.08",
"ecp_fix":"0.08",
"eccol":"chg",
"div":"0.34",
"yld":"1.26"
},
{
"id":"13756934",
"t":".IXIC",
"e":"INDEXNASDAQ",
"l":"5,193.49",
"l_fix":"5193.49",
"l_cur":"5,193.49",
"s":"0",
"ltt":"4:16PM EST",
"lt":"Nov 8, 4:16PM EST",
"lt_dts":"2016-11-08T16:16:29Z",
"c":"+27.32",
"c_fix":"27.32",
"cp":"0.53",
"cp_fix":"0.53",
"ccol":"chg",
"pcls_fix":"5166.1729"
}
]
I'm trying to deserialize this array and use but I keep getting the following error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'StockTicker.home+Class1' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Here is my class:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string id { get; set; }
public string t { get; set; }
public string e { get; set; }
public string l { get; set; }
public string l_fix { get; set; }
public string l_cur { get; set; }
public string s { get; set; }
public string ltt { get; set; }
public string lt { get; set; }
public DateTime lt_dts { get; set; }
public string c { get; set; }
public string c_fix { get; set; }
public string cp { get; set; }
public string cp_fix { get; set; }
public string ccol { get; set; }
public string pcls_fix { get; set; }
public string el { get; set; }
public string el_fix { get; set; }
public string el_cur { get; set; }
public string elt { get; set; }
public string ec { get; set; }
public string ec_fix { get; set; }
public string ecp { get; set; }
public string ecp_fix { get; set; }
public string eccol { get; set; }
public string div { get; set; }
public string yld { get; set; }
}
Here is what I'm trying to do:
var jsonObject1 = JsonConvert.DeserializeObject<Rootobject>(json);
var blah = jsonObject1.Property1[0].c;
I have no idea what to do at this point.

As the exception states, your outermost JSON container is an array -- a comma-delimited sequence of values surrounded by [ and ]. As such, it needs to be deserialized into a collection of some sort, as is explained in the docs. Thus you want to do:
var items = JsonConvert.DeserializeObject<Class1 []>(json);
var blah = items[0].c;
Sample fiddle.

Related

Object is always empty when deserialize on xamarin service

Have this service built on a xamarin app:
public class OpenWeatherMap<T>
{
private const string OpenWeatherApi = "http://api.openweathermap.org/data/2.5/weather?q=";
private const string Key = "653b1f0bf8a08686ac505ef6f05b94c2";
HttpClient _httpClient = new HttpClient();
// aqui podemos enviar directo a una ciudad hardcoded
public async Task<T> GetAllWeathers(string city)
{
var json = await _httpClient.GetStringAsync(OpenWeatherApi + city + "&APPID=" + Key);
var getWeatherModels = JsonConvert.DeserializeObject<T>(json);
return getWeatherModels;
}
}
When i check the model object is always empty. JSON is fine and my class matches perfectly my JSON model. I'm using Newtonsoft.Json.
This is my model:
public class WeatherMainModel
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public WeatherSubDetails[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("wind")]
public WeatherWindDetails Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public string Dt { get; set; }
[JsonProperty("sys")]
public WeatherSysDetails Sys { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public string Cod { get; set; }
}
public partial class Clouds // new
{
[JsonProperty("all")]
public string All { get; set; }
}
public partial class Coord // new
{
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public string Temp { get; set; }
[JsonProperty("pressure")]
public string Pressure { get; set; }
[JsonProperty("humidity")]
public string Humidity { get; set; }
[JsonProperty("temp_min")]
public string TempMin { get; set; }
[JsonProperty("temp_max")]
public string TempMax { get; set; }
}
public partial class WeatherSysDetails
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
}
public partial class WeatherSubDetails
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class WeatherWindDetails
{
[JsonProperty("speed")]
public string Speed { get; set; }
[JsonProperty("deg")]
public string Deg { get; set; }
}
I'm using visual studio community set for Latin America (Chile), so i tried changing every decimal field on the JSON to string on the model to avoid comma separation problems, but still, my object is coming empty no matter the JSON i inject to the deserializer.
Thanks in advance.

I am a new bee with JSON and I don't know how to perform serialization and deserialization in windows phone

get links will be like this - http//192.156.120.192/Projects/cricket/index.php/api/api
public class Player
{
public int playerId { get; set; }
public string playerName { get; set; }
public string specialization { get; set; }
public string battingHand { get; set; }
public string bowlingHand { get; set; }
public string bowlingType { get; set; }
public object genericId { get; set; }
public int homeTeamId { get; set; }
public int eligibleTeams { get; set; }
public object imageUrl { get; set; }
}
public class RootObject
{
public string methodName { get; set; }
public int errorCode { get; set; }
public string errorMessage { get; set; }
public List<Player> players { get; set; }
}
I am using Json.NET and it is super easy
// create a RootObject object
//..
string serializedRoot = JsonConvert.SerializeObject(myRootObject);
RootObject deserializedRoot = JsonConvert.DeserializeObject<Player>(serializedRoot);

JSON to a JSON array Cannot deserialize the current JSON object

I'm using Json.Net to DeserializeObject Json data into object/collection (list)
I'm not sure what I'm doing wrong and I have tried this:
List<LanguageObject> lang = JsonConvert.DeserializeObject<List<LanguageObject>>(jsonData);
and tried this:
LanguageObject.Results lang = JsonConvert.DeserializeObject<LanguageObject.Results>(jsonData);
I'm getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[LanguageObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'meta', line 1, position 8.
here my Json:
{"meta":
{
"status":200,
"message":[],
"resultSet":
{"id":"05"},
"pagination":
{
"count":2,
"pageNum":1,
"pageSize":2,
"totalPages":1,
"sort":"ordinal",
"order":"Asc",
"currentUri":null,
"nextUri":null
}
},
"results":
{
"id":0,
"name":
"Language",
"DName":null,
"qvalue":"language",
"language":null,
"mUsageCount":null,
"Ordinal":0,
"items":
[
{
"id":0,
"name":"English",
"DName":"English",
"qvalue":null,
"language":null,
"mUsageCount":null,
"Ordinal":0,
"items":[]
},
{
"id":0,
"name":"Spanish",
"DName":"Spanish;",
"qvalue":null,
"language":null,
"mUsageCount":null,
"Ordinal":0,"
items":[]
}
]
}}
LanguageObject.cs
Public class LanguageObject
{
public class ResultSet
{
public string id { get; set; }
}
public class Pagination
{
public int count { get; set; }
public int pageNum { get; set; }
public int pageSize { get; set; }
public int totalPages { get; set; }
public string sort { get; set; }
public string order { get; set; }
public object currentUri { get; set; }
public object nextUri { get; set; }
}
public class Meta
{
public int status { get; set; }
public List<object> message { get; set; }
public ResultSet resultSet { get; set; }
public Pagination pagination { get; set; }
}
public class Item
{
public int id { get; set; }
public string name { get; set; }
public string DName { get; set; }
public object qvalue { get; set; }
public object language { get; set; }
public object mUsageCount { get; set; }
public int Ordinal { get; set; }
public List<object> items { get; set; }
public List<object> __invalid_name__
items { get; set; }
}
public class Results
{
public int id { get; set; }
public string name { get; set; }
public object DName { get; set; }
public string qvalue { get; set; }
public object language { get; set; }
public object mUsageCount { get; set; }
public int Ordinal { get; set; }
public List<Item> items { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Results results { get; set; }
}
}
I don't see a LanguageObject class defined in your question. I do see a RootObject class, however. From what you have posted, you need to deserialize like this:
RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonData);
Then you can get the Results from the RootObject:
Results lang = root.Results;

How can I deserialization JSON in Windows Phone?

The first JSON is look like this
The second JSON is look like this
How can I deserialize them? I have been follow this example but it's not working.
Here's my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
PlaceList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
//For 2nd JSON
//w.DownloadStringAsync(
//new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));
}
These are classes for 1st JSON.
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObjectJSON1
{
public List<Place> Places { get; set; }
}
These are classes for JSON2
public class Address
{
public string street { get; set; }
public string postal_code { get; set; }
public string post_office { get; set; }
}
public class Image
{
public string id { get; set; }
public string filename { get; set; }
public string path { get; set; }
}
public class RootObjectJSON2
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string contact_person { get; set; }
public Address address { get; set; }
public List<Image> images { get; set; }
}
it looks that you should be deserializing object RootObjectJSON1 or RootObjectJSON2, e.g.:
var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
Also it seems that collection Places should be with lowercase p at beginning or you need to tell Json.NET that this property should be deserialized with different name, e.g.:
[JsonProperty(PropertyName="places")]
public List<Place> Places { get; set; }
Generally I tend to use arrays for deserialization (from my experience works better) so I'll suggest to rewrite it to this:
public class RootObjectJSON1
{
public Place[] places { get; set; }
}
There is very good tool named json2csharp available at http://json2csharp.com/ - just put sample of JSON there and it will spit out classes in C# (doesn't detect DateTime so you might need to change that).

How can I parse the following JSON for WP7 and bind to a listbox?

I'm having some trouble binding this json to a ListBox...The problem seems to happen in the ActivityTrack class/object of the JSON...i'm not sure what is not meshing...
{"collection":[{"type":"track","created_at":"2011/09/18 14:04:00 +0000","origin":{"id":23606164,"created_at":"2011/09/18 14:03:59 +0000","user_id":222927,"duration":342465,"commentable":true,"state":"finished","sharing":"public","tag_list":"garage usgarage soulfulhouse house deephouse deep","permalink":"pablo-cortez-when-i-need-u","description":"","streamable":true,"downloadable":false,"genre":"UK Garage","release":"","purchase_url":null,"label_id":null,"label_name":"","isrc":"","video_url":null,"track_type":"demo","key_signature":"","bpm":null,"title":"Pablo Cortez - When I Need U (Back To 90s Mix)","release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/23606164","permalink_url":"http://soundcloud.com/pablocortez/pablo-cortez-when-i-need-u","artwork_url":null,"waveform_url":"http://w1.sndcdn.com/wuiZilHRZhl6_m.png","user":{"id":222927,"permalink":"pablocortez","username":"Pablo Cortez","uri":"https://api.soundcloud.com/users/222927","permalink_url":"http://soundcloud.com/pablocortez","avatar_url":"http://i1.sndcdn.com/avatars-000000771958-y059w8-large.jpg?ca13f03"},"stream_url":"https://api.soundcloud.com/tracks/23606164/stream","user_playback_count":1,"user_favorite":false,"playback_count":28,"download_count":0,"favoritings_count":0,"comment_count":2,"attachments_uri":"https://api.soundcloud.com/tracks/23606164/attachments","sharing_note":{"text":"My new sounds","created_at":"2011/09/18 14:03:59 +0000"}},"tags":"affiliated"}],"next_href":"https://api.soundcloud.com/me/activities/track.json?cursor=86db5e5e-e1fe-11e0-9c69-0f0dad493cfc\\u0026limit=1","future_href":"https://api.soundcloud.com/me/activities/track?uuid%5Bto%5D=2d9c67ee-e22f-11e0-94fa-45aa16adeba3"}
Here is the class structure which i am trying to bind the JSON too
public class Activities
{
public ActivityTrack [] activities { get; set; }
public string next_href { get; set; }
public string future_href { get; set; }
}
public class ActivityTrack
{
public string type { get; set; }
public string created_at { get; set; }
public OriginActivityTrack origin { get; set; }
public string tags { get; set; }
}
public class OriginActivityTrack
{
public string id { get; set; }
public string created_at { get; set; }
public string user_id { get; set; }
public string duration { get; set; }
public string commentable { get; set; }
public string state { get; set; }
public string sharing { get; set; }
public string tag_list { get; set; }
public string permalink { get; set; }
public string description { get; set; }
public string streamable { get; set; }
public string downloadable { get; set; }
public string genre { get; set; }
public string release { get; set; }
public string purchase_url { get; set; }
public string label_id { get; set; }
public string label_name { get; set; }
public string isrc { get; set; }
public string video_url { get; set; }
public string track_type { get; set; }
public string key_signature { get; set; }
public string bpm { get; set; }
public string title { get; set; }
public string release_year { get; set; }
public string release_month { get; set; }
public string release_day { get; set; }
public string original_format { get; set; }
public string license { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string artwork_url { get; set; }
public string waveform_url { get; set; }
public SmallUser user { get; set; }
public string stream_url { get; set; }
public string user_playback_count { get; set; }
public string user_favorite { get; set; }
public string playback_count { get; set; }
public string download_count { get; set; }
public string favoritings_count { get; set; }
public string comment_count { get; set; }
public string attachments_uri { get; set; }
public SharingNote sharing_note;
}
public class SharingNote
{
public string text { get; set; }
public string created_at { get; set; }
}
public class SmallUser
{
public string id { get; set; }
public string permalink { get; set; }
public string username { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string avatar_url { get; set; }
}
This is the current code for binding to listbox:
private void ReadCallbackDashboard(IAsyncResult asynchronousResult)
{
lock (locker)
{
try
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 =
new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultString)))
{
if (ms != null)
{
var ser = new DataContractJsonSerializer(typeof(Activities));
Activities obj = (Activities)ser.ReadObject(ms);
userDashboardActivities = null;
userDashboardActivities = new ObservableCollection<ActivityTrack>();
for (int i = 0; i < obj.activities.Length; ++i)
{
userDashboardActivities.Add(obj.activities[i]);
}
if (userDashboardActivities.Count() == 0)
{
messageDashboard = "No Tracks Found";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
}
else
{
messageDashboard = "";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
UIThread.Invoke(() => dashboardBox.ItemsSource = userDashboardActivities);
}
}
}
}
}
catch (WebException we)
{
UIThread.Invoke(() => MessageBox.Show("Could not retrieve the latest. Internet down? Try a refresh."));
}
}
}
please check it out! Thanks in advance!
Answer as discovered in the comments.
You have called your property activities but the json calls it collection.