I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string
what am I doing wrong here? i'm trying to consume the ncaa data but I'm getting a bunch of \t and \n in my data, which makes it so I can't serialize it to an object. Here is my function, you can literally run this as it takes no credentials to get the data.
public string GetGameInfo(DateTime dt)
{
string content = string.Empty;
string url = "http://data.ncaa.com/jsonp/scoreboard/baseball/d1/2016/04/06/scoreboard.html";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(resStream))
{
content = sr.ReadToEnd();
}
return content;
}
/// <summary>
/// Summary description for Ncaa
/// </summary>
namespace Ncaa
{
public class callbackWrapper
{
public List<scoreboard> scoreboard { get; set; }
}
public class scoreboard
{
public DateTime day { get; set; }
public List<games> games { get; set; }
}
public class games
{
public string id { get; set; }
public string conference { get; set; }
public string gameState { get; set; }
public string startDate { get; set; }
public string startDateDisplay { get; set; }
public string startTime { get; set; }
public string startTimeEpoch { get; set; }
public string currentPeriod { get; set; }
public string finalMessage { get; set; }
public string gameStatus { get; set; }
public string periodStatus { get; set; }
public string downToGo { get; set; }
public string timeclock { get; set; }
public string network_logo { get; set; }
public string location { get; set; }
public string contestName { get; set; }
public string url { get; set; }
public string highlightsUrl { get; set; }
public string liveAudioUrl { get; set; }
public string gameCenterUrl { get; set; }
//public ChampInfo champInfo { get; set; }
//public IList<object> videos { get; set; }
public home home { get; set; }
public away away { get; set; }
}
public class home
{
public string teamRank { get; set; }
public IList<int> RHEBreakdown { get; set; }
public string iconURL { get; set; }
public string name { get; set; }
public string nameRaw { get; set; }
public string nameSeo { get; set; }
public string shortname { get; set; }
public string color { get; set; }
//public Social social { get; set; }
public string description { get; set; }
public string currentScore { get; set; }
public IList<string> scoreBreakdown { get; set; }
public string winner { get; set; }
}
public class away
{
public string teamRank { get; set; }
public IList<int> RHEBreakdown { get; set; }
public string iconURL { get; set; }
public string name { get; set; }
public string nameRaw { get; set; }
public string nameSeo { get; set; }
public string shortname { get; set; }
public string color { get; set; }
//public Social social { get; set; }
public string description { get; set; }
public string currentScore { get; set; }
public IList<string> scoreBreakdown { get; set; }
public string winner { get; set; }
}
}
protected void Page_Load(object sender, EventArgs e)
{
var json = GetGameInfo(DateTime.Now);
//this one doesn't work
//JsonConvert.DeserializeObject<Ncaa.callbackWrapper>(json);
//I tried removing the /ts and ns with no luck too
json = json.Replace("\t", string.Empty).Replace("\n", string.Empty);
JsonConvert.DeserializeObject<Ncaa.callbackWrapper>(json);
}
First of all, to answer why there's bunch of \ts and \ns in the response is because they ARE in your file. Those are respectively the tab character and the new line character.
I am not sure how you parse this , but most parsers should be able to handle this. In case you wrote your own, please post that code.
If the data returned will always be of format callback(JSON) you could strip the function call and simply parse the JSON using NewtonsoftJSON
EDIT: After reviewing the added code, I can notice that you are not stripping the function call. You should remove that and try again ( e.g. try removing everything until the first ocurrence of the { character and after last, or any other way you like )
Ok, so I did get it working. Doing this to the json helped.
json = json.Replace("callbackWrapper(", string.Empty).Replace(");", string.Empty);
Then, just parsing it as a scoreboard object, instead of a callback wrapper object.
here is my Get Set Method Class
public class RechargeGridDTO
{
public String from { get; set; }
public String to { get; set; }
public String errormsg { get; set; }
public String status { get; set; }
public RechargeInnerMsgGridInfo message { get; set; }
public String type { get; set; }
public String reqid { get; set; }
}
public class RechargeInnerMsgGridInfo
{
public String mob {get;set;}
public String rctype { get; set; }
public String rcservice { get; set; }
public String rcmobile { get; set; }
public String rcamt { get; set; }
public String rcpin { get; set; }
public String mytxid { get; set; }
public String optxid { get; set; }
public String txid { get; set; }
public String rcstatus { get; set; }
public String rcmsg { get; set; }
public String rctime { get; set; }
public String rcbal { get; set; }
public String rcsimbal { get; set; }
public String rcremark { get; set; }
public String rcchnnl { get; set; }
}
this is the json response I wanted to parse i-e:
msg = {
"from":"nishantuser",
"to":"smpp",
"errormsg":null,
"status":"s",
"message":
{
"mob":"9999999999",
"rctype":"Rr",
"rcservice":"Aircel",
"rcmobile":"8460149820",
"rcamt":"20",
"rcpin":"1234",
"mytxid":"4850",
"optxid":GUJNishant123,
"txid":null,
"rcstatus":s,
"rcmsg":null,
"rctime":null,
"rcbal":null,
"rcsimbal":null,
"rcremark":null,
"rcchnnl":null
},
"type":"RECHARGE",
"reqid":"4850"
}
when i am parsing this json Response then getting error...
var ResponseData = JsonConvert.DeserializeObject<RechargeGridDTO>(msg);
please give me the solution how i can parse this type of Response in using JsonConvert in C#
"optxid":GUJNishant123,
"rcstatus":s,
Those parts are not valid JSON. Strings need to be quoted:
"optxid":"GUJNishant123",
"rcstatus":"s",
Im new in developing windows phone app --> i have problem so i have tried all the possible solutions but with no vain:-
the application tried to take result from webservice the result come back like this:-
{"d":"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"LastTickTime\":\"\/Date(1396613678728)\/\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}"}
so i have tried to parse it but it give me errors after that i have tried locally removed the {"d":" and \"LastTickTime\":\"\/Date(1396613678728)\/\" from the string with no connection to webservice and its working fine i use this code :-
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
//Json classes
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public string UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var jsonString =
"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":-579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
RootObject jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
MessageBox.Show("hello " + jsonObject.Username + "" + jsonObject.UserId);
int val1 = Convert.ToInt16(jsonObject.UserId);
if (val1 > 0)
MessageBox.Show("You are logedin");
else
{
MessageBox.Show("Sorry Please login");
}
}
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
}
Please help me to parse all of the json result (locally i mean without conection to web)and what is the code to do that.
thank you all
First, your JSON is all a string property of "D". You can't deserialize it to RootClass. Second, your JSON contains invalid escape characters in the LastTickTime area. I removed both of these, and the JSON parses without errors of any kind. I just used a console app to test it.
var s = "{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
var foo = JsonConvert.DeserializeObject<RootObject>(s);
Console.WriteLine(foo.UserId); // Writes 579
UPDATE
If you have no control over what you get back, do the following:
Take the response and get rid of the / combination. As such:
string webResponse = "your long web response from the server";
webResponse = webResponse.Replace(#"\/", "/");
// If dynamic isn't in the phone subset, you'll need a class here containing "d" as a string.
var jsonOuter = JsonConvert.DeserializeObject<dynamic>(webResponse);
var jsonInner = JsonConvert.DeserializeObject<RootObject>(jsonOuter.d);
if (jsonInner.UserId > .....)
I got a json string from http://itunes.apple.com/lookup?id=796171602
this link always give me an array with only one Item. so instead of creating a class with root object and results array, I want to get the only first object and work with directly.
WebClient webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
string appJsonData = webClient.DownloadString("http://itunes.apple.com/lookup?id=796171602");
App app = new App();
JToken rootObject = JToken.Parse(appJsonData);
JToken appToken = rootObject["results"];
app = JsonConvert.DeserializeObject<App>(appJsonData);
when deserializing it, I get:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
when I create a c# class using jsonpack.com it works.
my custom object is this:
public class App : Entity
{
//it's not app id in the data base
[JsonProperty("trackId")]
public virtual int AppStoreId { get; set; }
[JsonProperty("trackViewUrl")]
public virtual string AppStoreLink { get; set; }
[JsonProperty("sellerName")]
public virtual string SellerName { get; set; }
[JsonProperty("artworkUrl60")]
public virtual string Icon { get; set; }
[JsonProperty("trackName")]
public virtual string Name { get; set; }
[JsonProperty("formattedPrice")]
public virtual string FormattedPrice { get; set; }
[JsonProperty("primaryGenreName")]
public virtual string Genre { get; set; }
[JsonProperty("Description")]
public virtual string Description { get; set; }
[JsonProperty("releaseNotes")]
public virtual string ReleaseNotes { get; set; }
[JsonProperty("releaseDate")]
public virtual DateTime ReleaseDate { get; set; }
[JsonProperty("userRatingCountForCurrentVersion")]
public virtual string UserRatingCountForCurrentVersion { get; set; }
[JsonProperty("averageUserRatingForCurrentVersion")]
public virtual string AverageUserRatingForCurrentVersion { get; set; }
[JsonProperty("fileSizeBytes")]
public virtual string FileSize { get; set; }
[JsonProperty("screenshotUrls")]
public virtual IList<string> IPhoneSceenShots { get; set; }
[JsonProperty("ipadscreenshotUrls")]
public virtual IList<string> IPadSceenShots { get; set; }
public App()
{
IPhoneSceenShots = new List<string>();
IPadSceenShots = new List<string>();
}
}
last night it works well, but today isn't working.
doesn anyone have any idea?
this code works for your json string
var obj = JsonConvert.DeserializeObject<RootObject>(appJsonData);
public class Result
{
public string kind { get; set; }
public List<object> features { get; set; }
public List<string> supportedDevices { get; set; }
public bool isGameCenterEnabled { get; set; }
public List<string> screenshotUrls { get; set; }
public List<object> ipadScreenshotUrls { get; set; }
public string artworkUrl60 { get; set; }
public string artworkUrl512 { get; set; }
public string artistViewUrl { get; set; }
public int artistId { get; set; }
public string artistName { get; set; }
public double price { get; set; }
public string version { get; set; }
public string description { get; set; }
public string currency { get; set; }
public List<string> genres { get; set; }
public List<string> genreIds { get; set; }
public string releaseDate { get; set; }
public string sellerName { get; set; }
public string bundleId { get; set; }
public int trackId { get; set; }
public string trackName { get; set; }
public string primaryGenreName { get; set; }
public int primaryGenreId { get; set; }
public string releaseNotes { get; set; }
public string formattedPrice { get; set; }
public string wrapperType { get; set; }
public string trackCensoredName { get; set; }
public List<string> languageCodesISO2A { get; set; }
public string fileSizeBytes { get; set; }
public string contentAdvisoryRating { get; set; }
public double averageUserRatingForCurrentVersion { get; set; }
public int userRatingCountForCurrentVersion { get; set; }
public string artworkUrl100 { get; set; }
public string trackViewUrl { get; set; }
public string trackContentRating { get; set; }
}
public class RootObject
{
public int resultCount { get; set; }
public List<Result> results { get; set; }
}
EDIT
var obj = JsonConvert.DeserializeObject<JObject>(appJsonData)["results"][0] as JObject;
var app = obj.ToObject <Result>();