How to save parts of a json in variable?

Asked

Viewed 307 times

0

I’m new with programming and have a project in Console Application, which returns the call of an API the Json of it. I would like to know which command I can only get a part of json with. For example:

      "amount": 4999,
      "currency": "BRL",
      "closed": true,
      "items": [
  • Just take the field amount: 4999, and save in a variable

Follow some information regarding the code, if you need any more information please let me know:

Method of the API call that returns Json

  • The console.write(response.content) returns the json that comes from the API, similar to the above example.
public class GetOrder
    {
        [HttpGet]
        public static void GetOrderId(string token, string url)
        {
            Authenticator auth = new Authenticator();
            Authenticator.Authorization();

            try
            {
                var client = new RestClient(url);
                //var request = new RestRequest(("orders/" + orderId), Method.GET, DataFormat.Json);
                var request = new RestRequest(("orders/"), Method.GET, DataFormat.Json);


                client.Authenticator = new HttpBasicAuthenticator(token, auth.BasicAuthPassword);
                var response = client.Get(request);
                client.Execute(request);
                Console.WriteLine(response.Content);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

Program.Cs

static void Main(string[] args)
        {
            // Le o appsettings e criar um objeto IConfiguration
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false)
                .Build();

            // Lê o valor da chave 
            var token = config.GetSection("Config:ApiTokenSecretQA").Value;
            var url = config.GetSection("Config:UrlApi").Value;

            // Passa como parâmetro
            GetOrder.GetOrderId(token, url);

            //GetOrder.GetOrderId();

            //CreateHostBuilder(args).Build().Run();
        }


        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddHostedService<Worker>();
                });
  • How to exit the command Console.WriteLine(response.Content);?

  • Welcome to the Sopt. I suggest you reread your question and try to rewrite it to explain more clearly what you intend to do and what problem you face. Besides the question is not clear, the code presented also does not make much sense.

  • @Henriquemiranda mentioned above, I edited the post.

  • @tvdias I edited the post, see if it got better to understand. I don’t know which part of the code can be more useful. The very question is how to save, for example, only a json line or only the value of a json field in a variable. It was clear?

3 answers

1

Basically to solve your problem we need to understand how JSON works. When you have a return that is in JSON format it will always be accompanied by a key and a value in format

key:value

This object can be Serialized and Deserialized through a class in C# in your example we would have a class similar to:

public class Exemplo
{
    public int Amount { get; set; }
    public string Currency { get; set; }
    public bool Closed { get; set; }
    public List<object> Items { get; set; }
}

NOTE: As I don’t know what the Items list is about I left as Object only to illustrate.

In the case when a return of an API occurs for example when we use a method to deserialize this JSON as for example:

JsonConvert.DeserializeObject<T>();

He will associate with Key with the property that has the same name.

In your case as you only want the Amount you can create a class that has only this property.

public class RetornoAPI
{
    public int Amount { get; set; }
}

Another output that can be used is with Newtonsoft Linq.

JObject resultado = JObject.Parse(json);
var value = resultado.GetValue("amount");
int amount = value.ToObject<int>();

In the Getvalue() the string has to be equal to JSON if it will not return Null value.

  • Thank you very much, you managed to solve my problem, and a great explanation!!

  • I’m glad I could help!

  • @Gabrielrio note that it is not necessary to manipulate json directly, since the RestSharp. By doing this it is still possible to opt for different serializers, such as the System.Text, built in no dotnet.

1

You can perform various manipulations using json objects. Thinking that the content of the HTTP response is a text (string) that contains a json that line of code below converts this text into a Jobject

JObject jsonObject = JObject.Parse(response.Content);

From that moment on you can manipulate Jobject thinking that JSON works with the logic of keys and values, being as follows:

{
"chave": valor,
...
}

jsonObject["chave"] -> Apresenta o valor

So, in your example, you can access the following way (In the second line you would be printing in the console the amount value, which in your example would be 4999:

JObject jsonObject = JObject.Parse(response.Content);

Console.WriteLine(jsonObject["amount"]);

So the last step would be to create a variable to store that value, thinking that the amount is a numeric value that can have decimal places, use some floating point, for example:

float amount = jsonObject["amount"];

If you want to deepen your code and make more manipulations with json, I suggest you take a look at serialization and Classes, to store more complex objects.

  • Thank you very much!!

0


The relevant part of the question is asking for a Rest api and deserialize its content.

For the code shown, only the part below must be taken into account:

var client = new RestClient(url);
var request = new RestRequest(("orders/"), Method.GET, DataFormat.Json);
//(...)
var response = client.Get(request);
client.Execute(request);

To do what you want just create a class with the properties you want to read. Ex:

public class Retorno
{
    public int Amount { get; set; }
    public string Currency { get; set; }
    public bool Closed { get; set; }
    public List<Item> Items { get; set; }
}

public class Item
{
    public string Id { get; set; }
    public string Type { get; set; }
}

And then change the call to the API to

var response = client.Execute<Retorno>(request);
var dados = response.Data;

The variable dados be the type Retorno and you can access the value in question dados.Amount.

  • Thank you very much! That’s exactly what I did! But now I have a problem that I need to access a field of one object that is inside another: &#xA;"currency": "BRL",&#xA; "closed": true,&#xA; "items": [&#xA; {&#xA; "id": "oi_jskapkspaks",&#xA; "type": "product"&#xA; }&#xA; Type this there, I cannot access the values inside the "Items array"

  • @Gabrielrio if that’s exactly what you did, you should mark the answer as accepted/upvote anyway. I will update the answer for more this your need, but it is important to always leave all the details in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.