Parsing a generic variable from a Json text - c#

I'm trying to parse the info from a json object obtained via api, but in this request, I'm trying to get just one variable. I just want to get the summonerLevel variable.
{
"test": {
"id":107537,
"name":"test",
"profileIconId":785,
"summonerLevel":30,
"revisionDate":1440089189000
}
}
I've been trying to it with this code and I know that if I write
p.summonerLevel = (int)(obj.test.summonerLevel)
it will work, but the problem is that test is not a static name, and it will be changing within each request I do. Any good example on how to do it?
Thanks
WebClient c = new WebClient();
string data = c.DownloadString("https://las.api.pvp.net/api/lol/las/v1.4/summoner/by-name/"+summonerName+"?api_key=<api-key>");
dynamic obj = JsonConvert.DeserializeObject(data);
p.summonerLevel = (int)(obj.tempName.summonerLevel);

Something like this?
int summonerLevel= (int)JObject.Parse(data).First.First["summonerLevel"];

Related

Newtonsoft.Json Usage in long trees

I'm trying so scrape some info from a JSON response but it fails; I think it may have to do with the way I'm making use of a library I'm new to.
Below is the JSON instance that I'm trying to get data from;
{
"profileChanges":[
{
"changeType":"fullProfileUpdate",
"profile":{
"stats":{
"attributes":{
"allowed_to_receive_gifts":true,
"allowed_to_send_gifts":true,
"ban_history":{},
//This is what I'm trying to scrape the EpicPCKorea string
"current_mtx_platform":"EpicPCKorea",
"daily_purchases":{},
"gift_history":{},
"import_friends_claimed":{},
"in_app_purchases":{
"fulfillmentCounts":{
"2E5AC9924F2247325BBB22AC9AF9965B":1
},
"receipts":[
"EPIC:543a35e70dde4e0aaf56a9e0b76c8f67"
]
},
"inventory_limit_bonus":0,
"mfa_enabled":false,
"monthly_purchases":{},
"mtx_affiliate":"",
"mtx_purchase_history":{},
"weekly_purchases":{}
}
},
"updated":"2018-12-06T14:37:27.797Z",
}
}
],
"profileChangesBaseRevision":31,
"serverTime":"2018-12-30T18:44:35.451Z"
}
Here, my code in C#;
//str4 is the json response that I just posted up.
dynamic json = JsonConvert.DeserializeObject(str4);
string platform = json.profileChanges.profile.stats.attributes.current_mtx_platform;
But it doesn't work at all.
I debugged it and found out this Exception:
'Newtonsoft.Json.Linq.JArray' does not contain a definition for 'profile'
What am I doing wrong and how can I fix it?
As mentioned in the comments under your question, profileChanges is an array so you need to specify which item in the array to access.
Are you sure the the below does not work? It works for me...
string platform = json.profileChanges[0].profile.stats.attributes.current_mtx_platform;

Set a Json Serialized Object into session. not able to parse it from the View

Just the Brief Code which is enough to explain my problem i guess.
Here is my c# code:
List<MaZone> ListZoneValues = new List<MaZone>();
ListZoneValues.Add(new MaZone()
{
ZoneIc = int.Parse(DataReader["ZoneIC"].ToString()),
ZoneName = DataReader["ZoneName"].ToString()
});
HttpContext.Session.SetString("ZoneDetails",JsonConvert.SerializeObject(ListZoneValues));
Here is my javascript code.
var ZoneDetailsVB = '#HttpContextAccessor.HttpContext.Session.GetString("ZoneDetails")';
JSON.parse(ZoneDetailsVB);
But the error im face is while Parsing the Json.
The Error was:
Uncaught SyntaxError: Unexpected token & in JSON at position 2
at JSON.parse (<anonymous>)
Json string Recieved:
[{"ZoneIc":1,"ZoneName":"Zone1"},{"ZoneIc":2,"ZoneName":"Zone1 & 2"},{"ZoneIc":3,"ZoneName":"Zone2"},{"ZoneIc":4,"ZoneName":"Zone4"},{"ZoneIc":5,"ZoneName":"Zone5"},{"ZoneIc":6,"ZoneName":"Zone 6"},{"ZoneIc":7,"ZoneName":"Zone Num 7"}]
Thanks in Advance.
If you are using jQuery, you could do something like this
function htmlDecode(value) {
return $("<textarea/>").html(value).text();
}
var ZoneDetailsVB = '#HttpContextAccessor.HttpContext.Session.GetString("ZoneDetails")';
JSON.parse(htmlDecode(ZoneDetailsVB));
You can also use he library https://github.com/mathiasbynens/he
Third solution is to use
Html.Raw
var ZoneDetailsVB = '#(Html.Raw(HttpContextAccessor.HttpContext.Session.GetString("ZoneDetails").ToString()))'

How can I determine the class of an XML serialized object in C# before I deserialize it?

I have a server that accepts requests as XML serialized objects which could be any of 10 or so different Classes. Of course in order for the server to process the request, it must first de-serialize the XML string back into an object. To do that, it needs to know what class the object came from to choose the correct de-serializer and re-construct the object. So it would be good to be able to just quickly inspect the XML string before attempting to de-serialize it to get the object type and then select the appropriate de-serializer.
I have been using the following code, but, like the song goes, "I know there's got to be a better way..." Any suggestions or insight would be appreciated.
private void button1_Click(object sender, EventArgs e)
{
//any class - does not matter - create an object
SomeClass tc = new SomeClass();
//populate it
tc.i = 5;
tc.s = "Hello World";
tc.d = 123.456;
//Serialize it to XML
StringWriter xml = new StringWriter();
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(SomeClass));
x.Serialize(xml, tc);
//Extract the Class name and show the XML to the user without de-serializing it
textBox1.Text = GetClassNameFromXMLSerializedString(xml.ToString());
}
private string GetClassNameFromXMLSerializedString(string xml)
{
//The class name is somewhere in the xml
string classname = xml;
//get the start of class name
classname = xml.Substring(classname.IndexOf('>') + 4);
//get the class name which is terminated by a space
classname = classname.Substring(0, classname.IndexOf(' '));
//return it
return classname;
}
The XML Deserializer does not need to know what type it is before deserializing. The MSDN Article about the Deserialize method has some useful information about it and of course it has a code snippet, which I've put below.
I think you might have confused yourself with the fact that the server will deserialize it to an object, but then won't know what to do with it. You can always do a switch case for the result of the ReturnedObject.GetType() method and work out what you need to do with it.
You can just serialize it to an object like this:
var ReturnedObject = XMLSerializer.Deserialize(reader);
Then you can go ahead and do
switch (ReturnedObject.getType())
{
case MyClass:
// Insert code here
case AnotehrClass:
//Do something else here for another class
}
If you really want to you can read the 3rd element like this:
using (XmlReader xr = XmlReader.Create(GenerateStreamFromString(xml.ToString())))
{
xr.Read();
xr.Read();
xr.Read();
textBox1.Text = xr.Name;
}
Using this helper function:
public static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}
All checks omitted..
If you want to you can test if the 1st element is xml and the 2nd one is empty.
I'm not really sure if this is a good idea.
XDocument xd = XDocument.Parse(xml.ToString()); switch (xd.Root.Name.ToString()) { case "Class1": //do something break; case "Class2": //do something break; }

Newtonsoft read array in C#

I'm trying to get an entry of a json array into a messagebox but i can't seem to get the entry it always gives me
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: C. Path '', line 0, position 0.'
No matter what i do here is the json i use:
[
{
"code": 200,
"token": "yourtokenhere",
"id": "youridhere",
"user": "user",
"message": "Successfully connected"
}
]
Here is what i got so far:
string json = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\zero.json";
login fetch = new login();
Newtonsoft.Json.JsonConvert.PopulateObject(json, fetch);
MessageBox.Show(fetch.user);
And here is the C# class i made:
class login
{
public string code;
public string token;
public string id;
public string user;
public string message;
}
Thanks in advance!
EDIT: The full code is available here
Your problem is two-fold.
One issue is that you want to deserialize an array into an object. Other answers here already have addressed this issue.
The other issue, the one responsible for the error in your question, is that you used the Newtonsoft.Json.JsonConvert.PopulateObject method incorrectly. Look at its documentation:
public static void PopulateObject(
string value,
Object target
)
Parameters
value
Type: SystemString
The JSON to populate values from.
target
Type: SystemObject
The target object to populate values onto.
Note that this method expects the Json string data as first argument, not a file path!
So what happens in your code is the variable json gets assigned a file path to your Json file (string json = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\zero.json";). The string variable json will now have a content like #"C:\Users\UserName\AppData\Roaming\zero.json".
Your code passes this string as json data to the PopulateObject() method. But since this string is not json data (it's just the file path), PopulateObject() fails. (Note that the error message complains about the json data starting unexpectedly with a C.)
One possibility of implementing what you want to do is to first read the Json file content into a string, and then pass this to the Json deserializer (in the same way as demonstrated by the other answers):
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\zero.json";
string json = File.ReadAllText(filePath);
List<login> fetch = Newtonsoft.Json.JsonConvert.DeserializeObject<List<login>>(json);
JSON data is an array and you are trying to deserialize it into an object.
Try below code:
List<login> fetch = Newtonsoft.Json.JsonConvert.DeserializeObject<List<login>>(json);
Please check
JsonConvert.DeserializeObject

How to find the other part of a string

I'm trying to make C# program that gets a line on a website and use it.
Unfortunately, I don't know the full line on the site. I only know "steam://joinlobby/730/". Although, what comes after "/730/" is always different.
So i need help getting the full line that comes after it.
What I've got:
public void Main()
{
WebClient web = new WebClient();
// here is the site that i want to download and read text from it.
string result = web.DownloadString("http://steamcommunity.com/id/peppahtank");
if (result.Contains("steam://joinlobby/730/"))
{
//get the part after /730/
}
}
I can tell you that it always ends with "xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxx"
so: steam://joinlobby/730/xxxxxxxxx/xxxxxxxx.
What's to prevent you from just splitting the string on '/730/'?
result.Split(#"/730/")[1]
https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
The easiest method for this particular case would be to take the first part, and then just skip that many characters
const string Prefix = #"steam://joinlobby/730/";
//...
if(result.StartsWith(Prefix))
{
var otherPart = result.SubString(Prefix.Length);
// TODO: Process other part
}
Make sure your result is not null and begins with steam://joinlobby/730/
if(string.IsNullOrWhiteSpaces(result) && result.StartsWith("steam://joinlobby/730/"))
{
string rest = result.SubString(("steam://joinlobby/730/").Length);
}

Categories