Hey all I am trying to figure this IGDB api out. I'm sure its powerful but it seems difficult to know what needs to be called and how since they don't have very good examples in their documents.
So as an example say I am looking to get the box art and game info from the game "Mortal Kombat" and that I need it from the SNES version.
Doing a normal search on their website brings up a lot of different Mortal Kombat.
The Mortal Kombat that I am needing for the SNES is the 2nd to last here in the image. Mortal Kombat (1992).
So I first have code to get id, cover, genres, name, platforms and screenshots:
public partial class Gameinfo
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("cover")]
public long Cover { get; set; }
[JsonProperty("genres")]
public long[] Genres { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("platforms")]
public long[] Platforms { get; set; }
[JsonProperty("screenshots")]
public long[] Screenshots { get; set; }
}
using (var client = new HttpClient()) {
using (var httpClient = new HttpClient { BaseAddress = baseAddress }) {
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("user-key", "##########################");
using (
var response = await httpClient.GetAsync("games?search=" + HttpUtility.UrlEncode(game) + "&fields=*")
)
{
string responseData = await response.Content.ReadAsStringAsync();
gameData = JsonConvert.DeserializeObject<List<Gameinfo>>(responseData);
System.Diagnostics.Debug.WriteLine(gameData);
}
}
}
The JSON response to the above is:
You can see the first hit is Mortal Kombat II and the second is the one I am looking for, the original Mortal Kombat. So from the code above I get 2 main things I need in order to search "deeper". The Game ID and the Platforms ID(s). But with saying that - there lye's the problem. I am unable to just search for Mortal Kombat and automatically get the correct 1992 version.
So without knowing the date that a game came out how can I search for the correct game with the needed platform of SNES?
UPDATE 1
So I tried doing the following:
using (
var response = await httpClient.GetAsync("games/?search=" +
HttpUtility.UrlEncode("mortal kombat") +
"&fields=name,platforms.name&where platforms.id = 19")
But I always end up with the same data no matter what:
[
{
"id": 81899,
"name": "Mortal Kombat \u0026 Mortal Kombat II",
"platforms": [
{
"id": 22,
"name": "Game Boy Color"
}
]
},
{
"id": 119,
"name": "Mortal Kombat",
"platforms": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 9,
"name": "PlayStation 3"
},
{
Hi I have worked on IGDB Api. I think you need to get a game with specific platform.
All you need to where only platform filter. The following query fetches all games with platform id 130 (I don't know which platform is. You may change SNES platform id).
search "Mortal Kombat";
f name,popularity,rating,cover.image_id,platforms;
s popularity desc;
w platforms = (130) & category = 0;
l 50;
o 100;
Related
I have a json file and I deserialised it as shown in the code below. Some context, dex is a robot and it has information such as battery and so on as shown in the json file below. I want to read the battery status for the robot that the user selected ( robot).
This is my code, currently im only accessing data.dex but i want to change it to whichever data.robot, where robot is a variable
var data = JsonConvert.DeserializeObject<Root>(json);
var robot = queryDetails2.Amr;
var text =$"";
if (data.dex.battery.status == "good")
{
text = $"{queryDetails2.Amr}'s battery is in good condition. ";
}
This is the json file:
{
"dex":
{
"current_job":
{"job":null, "task": null, "location": null},
"battery":
{"name":"battery", "status": "good", "value": "100"},
},
"dex_1":
{
"current_job":
{"job":null, "task": null, "location": null},
"battery":
{"name":"battery", "status": "good", "value": "100"},
},
"dex_2":
{
"current_job":
{"job":null, "task": null, "location": null},
"battery":
{"name":"battery", "status": "good", "value": "100"},
}
}
I wanted to use the GetMethod or the solution as suggested in this question (https://stackoverflow.com/questions/53076743/how-to-access-variable-of-a-nested-functions-in-python[1]).
However, im getting errors like it does not have a method. Now im confused, was it because i used var? but the deserialised method converts the json to an object though..
Anyway, how should i approach this?
Assuming that you have 3 robots with different names: dex, dex_1 and dex_2, you should reorganize your solution to treat the json data as a list of Robots instead of 3 separate variables for each robot.
To do this, first your json should look like this:
{
"robots":[
{
"name":"dex",
"current_job":{
"job":null,
"task":null,
"location":null
},
"battery":{
"name":"battery",
"status":"good",
"value":"100"
}
},
{
"name":"dex_1",
"current_job":{
"job":null,
"task":null,
"location":null
},
"battery":{
"name":"battery",
"status":"good",
"value":"100"
}
},
{
"name":"dex_2",
"current_job":{
"job":null,
"task":null,
"location":null
},
"battery":{
"name":"battery",
"status":"good",
"value":"100"
}
}]
}
Next, update your serialization classes. Add a field called name in the Robot class or whatever class type you currently have for data.dex. In Root, remove the "dex" fields and add a List<Robot>.
public class Root
{
public List<Robot> robots { get; set; }
}
public class Robot
{
public string name { get; set; }
public Job current_job { get; set;}
public Battery battery{ get; set; }
}
Now you can write whatever logic to get the right robot data. Here is an example using System.Linq:
var robotName = "dex_2";
var robotInfo = data.robots.First(x => x.name.Equals(robotName));
var text = $"{robotName}'s battery is in {robotInfo.battery.status} condition.";
Im writing an API automation test with RestSharp.Any kind of help will be greatly appreciated!
I'm getting data values from the response & I need to write few values to my json file (which I will use for another test putting them as a body).
I managed to get 1 value from JArray but I need 2 more values and I cant wrap my head around how to do that.
Im attaching my api test code & the data I get from the response + the data I managed to write into my json file.
The value that I managed to get: FsNumber (declared it as financialNumber). What I need to add to the json: subjectName + subjectCode (they will be declared as companyName/companyCode). How do I access "Query" list with SubjectName/SubjectCode?
TEST
var queryResult = client.Execute<object>(request);
var data = JsonConvert.SerializeObject(queryResult.Data);
var jsonParse = JToken.Parse(data);
var fsObject = jsonParse.Value<JToken>("FinanceReportList");
var fsArray = fsObject.Value<JArray>("List");
foreach (var fs in fsArray)
{
var cfn = fs.Value<string>("FsNumber");
var queryObject = new DataQuery
{
financialNumber = cfn,
};
var queryObjectString = JsonConvert.SerializeObject(queryObject);
File.WriteAllText(#"C:\Users\TestAPI\myJsonWithValues.json", queryObjectString);
}
Data I get from the response:
{
"RequestDate": "2021-07-16",
"Message": "Active",
"ProductNumber": 666,
"Language": "EN",
"RequestId": "reqID666",
"Query": {
"SubjectCode": "MY-SUBJECT",
"SubjectName": "MY-NAME"
},
"FinanceReportList": {
"List": [
{
"FsNumber": "MY-NUMBER",
"Year": 2021,
So far I managed to get FsNumber to my myJsonWithValues.json file as this:
{"financialNumber":"MY-NUMBER","companyName":null,"companyCode":null}
What Im trying to do is, my json should look like
{"financialNumber":"MY-NUMBER","companyName":MY-NAME,"companyCode":MY-CODE}
You have to access "Query" object
var fsQuery = jsonParse.Value<JToken>("Query")
and use Children() method to access properties of "Query"
var children = fsQuery.Children();
It is a good practice to implement a class that encapsulates your resonse and deserialize it with JsonConvert.Deserialize eg.
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
Account account = JsonConvert.DeserializeObject<Account>(json);
Instead of using JObjects
I'm trying to make an API using .NET Core 3.1 with C# programming language which utilizes Firebase real-time database from Google through FireSharp Nu-Get package. When I ran it, I got this exception: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. I read here that I can just install Microsoft.AspNetCore.Mvc.NewtonsoftJson package and ignore the reference loop handling, which works fine. But the data format looks unreadable, very hard to deserialize, and way too long:
{
"stateMachine": {
"<>1__state": 0,
"<>t__builder": {},
"bpjs": "12345678",
"reservationTime": "24-11-2020",
"<>4__this": {}
},
"context": {},
"moveNextAction": {
"method": {
"name": "MoveNext",
"declaringType": ...
...
((lots of irrelevant things))
...
}
},
"result": {
"queueNumber": "1",
"bpjs": "12345678",
"name": "Addi",
"poli": "Umum",
"reservationTime": "24-11-2020",
"status": "Queueing"
},
"id": 2,
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false}
Before this, I already tried to do some mapping and not directly use my data model by following this video's tutorial on doing DTOs, but it didn't work most likely because I don't use SQL Database.
Now I'm trying to use this API on a Flutter app. Is there anyway for me to maybe do some minor changes on my API code (anything that doesn't involve completely changing the database to SQL) to reformat my response? Or maybe a way to just partly deserialize my response, since I only need the "result" part and not anything else?
Edit:
This is my main code to get the data:
public async Task<QueueData> GetQueueData(string bpjs, string reservationTime)
{
//set up connection
IFirebaseConfig config = new FirebaseConfig
{
AuthSecret = myAuthSecret,
BasePath = myBasePath
};
IFirebaseClient client = new FireSharp.FirebaseClient(config);
//checkqueuenumber
string queueCounter = await QueueDbConnection.CheckQueueNumber(reservationTime, client);
//getresult
QueueData result = await QueueDbConnection.GetResult(bpjs, reservationTime, queueCounter, client);
return result;
}
this is my controller to call the function above:
[HttpGet("{bpjs}/{reservationTime}")]
public ActionResult<QueueData> GetQueueData(string bpjs, string reservationTime)
{
var queueData = _repository.GetQueueData(bpjs, reservationTime);
return Ok(queueData);
}
This is my model for the QueueData, which is the type I'm trying to return as response:
public class QueueData
{
[Required]
public string QueueNumber { get; set; }
[Required]
public string BPJS { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Poli { get; set; }
[Required]
public string ReservationTime { get; set; }
[Required]
public string Status { get; set; }
}
this is another model class called control to monitor the number of people queueing each day:
public class QueueCounter
{
[Required]
public string q { get; set; }
}
So, I solved this. I went back to here and apparently someone said the error I got in the first place was because not all async functions had been waited or handled properly. So I went through my codes once again and finally found the problem in my controller. After I made my controller async then changed the return type into Task<ActionResult>, everything went perfectly fine!
I currently have a Web API that implements a RESTFul API. The model for my API looks like this:
public class Member
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Created { get; set; }
public DateTime BirthDate { get; set; }
public bool IsDeleted { get; set; }
}
I've implemented a PUT method for updating a row similar to this (for brevity, I've omitted some non-relevant stuff):
[Route("{id}")]
[HttpPut]
public async System.Threading.Tasks.Task<HttpResponseMessage> UpdateRow(int id,
[FromBody]Models.Member model)
{
// Do some error checking
// ...
// ...
var myDatabaseEntity = new BusinessLayer.Member(id);
myDatabaseEntity.FirstName = model.FirstName;
myDatabaseEntity.LastName = model.LastName;
myDatabaseEntity.Created = model.Created;
myDatabaseEntity.BirthDate = model.BirthDate;
myDatabaseEntity.IsDeleted = model.IsDeleted;
await myDatabaseEntity.SaveAsync();
}
Using PostMan, I can send the following JSON and everything works fine:
{
firstName: "Sara",
lastName: "Smith",
created: "2018/05/10",
birthDate: "1977/09/12",
isDeleted: false
}
If I send this as my body to http://localhost:8311/api/v1/Member/12 as a PUT request, the record in my data with ID of 12 gets updated to what you see in the JSON.
What I would like to do though is implement a PATCH verb where I can do partial updates. If Sara gets married, I would like to be able to send this JSON:
{
lastName: "Jones"
}
I would like to be able to send just that JSON and update JUST the LastName field and leave all the other fields alone.
I tried this:
[Route("{id}")]
[HttpPatch]
public async System.Threading.Tasks.Task<HttpResponseMessage> UpdateRow(int id,
[FromBody]Models.Member model)
{
}
My problem is that this returns all the fields in the model object (all of them are nulls except the LastName field), which makes sense since I am saying I want a Models.Member object. What I would like to know is if there is a way to detect which properties have actually been sent in the JSON request so I can update just those fields?
I hope this helps using Microsoft JsonPatchDocument:
.Net Core 2.1 Patch Action into a Controller:
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody]JsonPatchDocument<Node> value)
{
try
{
//nodes collection is an in memory list of nodes for this example
var result = nodes.FirstOrDefault(n => n.Id == id);
if (result == null)
{
return BadRequest();
}
value.ApplyTo(result, ModelState);//result gets the values from the patch request
return NoContent();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex);
}
}
Node Model class:
[DataContract(Name ="Node")]
public class Node
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "node_id")]
public int Node_id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "full_name")]
public string Full_name { get; set; }
}
A valid Patch JSon to update just the "full_name" and the "node_id" properties will be an array of operations like:
[
{ "op": "replace", "path": "full_name", "value": "NewNameWithPatch"},
{ "op": "replace", "path": "node_id", "value": 10}
]
As you can see "op" is the operation you would like to perform, the most common one is "replace" which will just set the existing value of that property for the new one, but there are others:
[
{ "op": "test", "path": "property_name", "value": "value" },
{ "op": "remove", "path": "property_name" },
{ "op": "add", "path": "property_name", "value": [ "value1", "value2" ] },
{ "op": "replace", "path": "property_name", "value": 12 },
{ "op": "move", "from": "property_name", "path": "other_property_name" },
{ "op": "copy", "from": "property_name", "path": "other_property_name" }
]
Here is an extensions method I built based on the Patch ("replace") specification in C# using reflection that you can use to serialize any object to perform a Patch ("replace") operation, you can also pass the desired Encoding and it will return the HttpContent (StringContent) ready to be sent to httpClient.PatchAsync(endPoint, httpContent):
public static StringContent ToPatchJsonContent(this object node, Encoding enc = null)
{
List<PatchObject> patchObjectsCollection = new List<PatchObject>();
foreach (var prop in node.GetType().GetProperties())
{
var patch = new PatchObject{ Op = "replace", Path = prop.Name , Value = prop.GetValue(node) };
patchObjectsCollection.Add(patch);
}
MemoryStream payloadStream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(patchObjectsCollection.GetType());
serializer.WriteObject(payloadStream, patchObjectsCollection);
Encoding encoding = enc ?? Encoding.UTF8;
var content = new StringContent(Encoding.UTF8.GetString(payloadStream.ToArray()), encoding, "application/json");
return content;
}
}
Noticed that tt also uses this class I created to serialize the PatchObject using DataContractJsonSerializer:
[DataContract(Name = "PatchObject")]
class PatchObject
{
[DataMember(Name = "op")]
public string Op { get; set; }
[DataMember(Name = "path")]
public string Path { get; set; }
[DataMember(Name = "value")]
public object Value { get; set; }
}
A C# example of how to use the extension method and invoking the Patch request using HttpClient:
var nodeToPatch = new { Name = "TestPatch", Private = true };//You can use anonymous type
HttpContent content = nodeToPatch.ToPatchJsonContent();//Invoke the extension method to serialize the object
HttpClient httpClient = new HttpClient();
string endPoint = "https://localhost:44320/api/nodes/1";
var response = httpClient.PatchAsync(endPoint, content).Result;
Thanks
PATCH operations aren't usually defined using the same model as the POST or PUT operations exactly for that reason: How do you differentiate between a null, and a don't change. From the IETF:
With PATCH, however, the enclosed entity contains a set of
instructions describing how a resource currently residing on the
origin server should be modified to produce a new version.
You can look here for their PATCH suggestion, but sumarilly is:
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]
#Tipx's answer re using PATCH is spot on, but as you've probably already found, actually achieving that in a statically typed language like C# is a non-trivial exercise.
In the case where you're using a PATCH to represent a set of partial updates for a single domain entity (e.g. to update the first name and last name only for a contact with many more properties) you need to do something along the lines of looping each instruction in the 'PATCH' request and then applying that instruction to an instance of your class.
Applying an individual instruction will then comprise of
Finding the property of the instance that matches the name in the
instruction, or handling property names you weren't expecting
For an update: Trying to parse the value submitted in the patch into the instance property and handling the error if e.g. the instance property is a bool but the patch instruction contains a date
Deciding what to do with Add instructions as you can't add new properties to a statically typed C# class. One approach is to say that Add means "set the value of the instance's property only if property's existing value is null"
For Web API 2 on the full .NET Framework the JSONPatch github project looks to make a stab at providing this code, although it doesn't look like there's been a lot of development on that repo recently and the readme does state:
This is still very much an early project, don't use it in production
yet unless you understand the source and don't mind fixing a few bugs
;)
Things are simpler on .NET Core as that has a set of functionality to support this in the Microsoft.AspNetCore.JsonPatch namespace.
The rather useful jsonpatch.com site also lists out a few more options for Patch in .NET:
Asp.Net Core JsonPatch (Microsoft official implementation)
Ramone (a framework for consuming REST services, includes a JSON Patch implementation)
JsonPatch (Adds JSON Patch support to ASP.NET Web API)
Starcounter (In-memory Application Engine, uses JSON Patch with OT for client-server sync)
Nancy.JsonPatch (Adds JSON Patch support to NancyFX)
Manatee.Json (JSON-everything, including JSON Patch)
I need to add this functionality to an existing Web API 2 project of ours, so I'll update this answer if I find anything else that's useful while doing that.
I wanted to achieve exactly the same thing, but used a different method to others described here. I've created a working repo using this if you want to check it out:
https://github.com/emab/patch-example
If you have the following two models:
Database model
public class WeatherDBModel
{
[Key]
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
public double Temperature { get; set; }
public double WindSpeed { get; set; }
public double Rain { get; set; }
public Weather(int id, string city, string country, double temperature, double windSpeed, double rain)
{
Id = id;
City = city;
Country = country;
Temperature = temperature;
WindSpeed = windSpeed;
Rain = rain;
}
}
Update model
Containing exact names of database model properties. Includes properties which can be updated
public class WeatherUpdateModel
{
public string? City { get; set; }
public string? Country { get; set; }
public double Temperature { get; set; }
public double WindSpeed { get; set; }
public double Rain { get; set; }
}
This update model is sent to the service layer along with the id of the object you'd like to update.
You can then implement the following method in your repository layer which maps any non-null values from the updateModel into an existing entity if it has been found:
public Weather Update(int id, WeatherUpdate updateObject)
{
// find existing entity
var existingEntity = _context.Weather.Find(id);
// handle not found
if (existingEntity == null)
{
throw new EntityNotFoundException(id);
}
// iterate through all of the properties of the update object
// in this example it includes all properties apart from `id`
foreach (PropertyInfo prop in updateObject.GetType().GetProperties())
{
// check if the property has been set in the updateObject
// if it is null we ignore it. If you want to allow null values to be set, you could add a flag to the update object to allow specific nulls
if (prop.GetValue(updateObject) != null)
{
// if it has been set update the existing entity value
existingEntity.GetType().GetProperty(prop.Name)?.SetValue(existingEntity, prop.GetValue(updateObject));
}
}
_context.SaveChanges();
return existingEntity;
}
Using this method you can change your models without worrying about the update logic, as long as you ensure that the UpdateModel is kept up-to-date with the database model.
If a property of your object was omitted in your JSON, ASP.NET won't "set" that property on the object, the property will have its default value. In order to know which properties were sent with the JSON object you need to have a way to detect which properties of the object were set.
In order to detect which properties have "actually been sent" with the JSON object, you can modify your Member class to contain a collection of property names that were "set". Then, for all properties that you want to be able to know if they were sent in the JSON object make that when the property is set the name of the property should be added to the collection of set properties.
public class Member
{
private string _firstName;
private string _lastName;
...
private bool _isDeleted;
public string FirstName
{
get => _firstName;
set
{
_firstName = value;
_setProperties.Add(nameof(FirstName));
}
}
public string LastName
{
get => _lastName;
set
{
_lastName = value;
_setProperties.Add(nameof(LastName));
}
}
...
public bool IsDeleted
{
get => _isDeleted;
set
{
_isDeleted= value;
_setProperties.Add(nameof(IsDeleted));
}
}
private readonly HashSet<string> _setProperties = new HashSet<string>();
public HashSet<string> GetTheSetProperties()
{
return new HashSet<string>(_setProperties);
}
}
In the UpdateRow method you can now check whether a property was sent in the JSON by checking if it is in the _setProperties collection. So if you want to see if the LastName was sent in the JSON just do
bool lastNameWasInJson = model.Contains(nameof(model.LastName));
Following up to Avid Learners approach. I found this easy to add to an existing PUT method.
Alternatively to avoid loading twice you could apply update operations and then before saving apply the patch, but I'd rather load twice and have simple code.
public ResultModel Patch(UpdateModel model)
{
var record = LoadAsUpdateModel(model.Id);
if (record == null) return null;
foreach(var propertyName in model.SetProperties())
{
var property = model.GetType().GetProperty(propertyName);
property.SetValue(record, property.GetValue(model));
}
return Update(record);
}
I am trying to match Blockchain JSON Api response right way, but it seems like I just can't do it. Blockchain API Response looks like that:
{
"addresses": [
{
"balance": 1400938800,
"address": "1Q1AtvCyKhtveGm3187mgNRh5YcukUWjQC",
"label": "SMS Deposits",
"total_received": 5954572400
},
{
"balance": 79434360,
"address": "1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq",
"label": "My Wallet",
"total_received": 453300048335
},
{
"balance": 0,
"address": "17p49XUC2fw4Fn53WjZqYAm4APKqhNPEkY",
"total_received": 0
}
]
}
Basically, like you can see. For each address is each line, on C# ReadToEnd(), gives me it messed up. But basically I am trying that, if there is label SMS Deposits example, then from "that line" it will take that Address, no where else. Example: label is Peter, then it takes address only from Peter line, not any other line. How could I do that? Here is also my code:
listAddresses.Method = "GET";
HttpWebResponse listAddressesResp = (HttpWebResponse)listAddresses.GetResponse();
StreamReader listAddressesSR = new StreamReader(listAddressesResp.GetResponseStream());
var resultListAddresses = listAddressesSR.ReadToEnd();
if (resultListAddresses.Contains(name))
{
Regex SuiWillThatWork = new Regex("\"address\":\"[A-Za-z0-9]+");
var TestingVol2 = SuiWillThatWork.Match(resultListAddresses).Value;
TestingVol2 = TestingVol2.Replace("\"address\":\"", "");
address = TestingVol2;
MessageBox.Show(resultListAddresses);
MessageBox.Show(address);
}
Don't use regex for something that already has a really nice parser developed. Go do yourself a favor and Install-Package Newtonsoft.Json and try something like the following:
First, establish objects that match the response coming back. If you're lazy, there are tools available (such as json2csharp.com) which make this very easy. For your response, how about something like the following:
class ServerResponse
{
[JsonProperty("addresses")]
public List<AddressResponse> Addresses { get; set; }
}
class AddressResponse
{
[JsonProperty("balance")]
public long Balance { get; set; }
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("total_received")]
public long TotalReceived { get; set; }
}
Note: You don't have to go the JsonPropertyAttribute way, but I like to make my models follow naming conventions.
Next, we need to deserialize the response into our new object. Using Newtonsoft, it's as easy as:
var response = JsonConvert.DeserializeObject<ServerResponse>(jsonResponse);
You now have a fully hydrated object:
ServerResponse
Addresses (List<AddressResponse> (3 items))
Balance Address Label TotalReceived
1400938800 1Q1AtvCyKhtveGm3187mgNRh5YcukUWjQC SMS Deposits 5954572400
79434360 1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq My Wallet 453300048335
0 17p49XUC2fw4Fn53WjZqYAm4APKqhNPEkY null 0
To get back to the problem at hand, now we can look for "SMS Deposits" and retrieve the address:
var response = JsonConvert.DeserializeObject<ServerResponse>(jsonResponse);
var smsDeposits = response.Addresses.FirstOrDefault(x => x.Label == "SMS Deposits");
if (smsDeposits != null)
{
MessageBox.Show(smsDeposits.Address);
}