Home > Net >  How to get data value in string C#
How to get data value in string C#

Time:08-24

I have an object like this. How can I parse the Name Surname from this object?

Object

{
    "HasError":false,
    "AlertType":"success",
    "AlertMessage":"Operation has completed successfully",
    "ModelErrors":[],
    "Data":{
        "Count":1,
        "Objects":
        [{
            "Id":291031530,
            "FirstName":"Alp",
            "LastName":"Uzan",
            "MiddleName":"",
            "Login":"alp"
        }]
    }
}  

I'm getting this data to an external api using HttpClient but I can't parse it by values. Can you help with this, the type of data is System.String

CodePudding user response:

If you use c#, save output in string and serialize, usa this library

using Newtonsoft.Json;

JObject json = JObject.Parse(str);

string Name= json.Data.Objects[0].FirstName

string Surname = json.Data.Objects[0].Lastname

CodePudding user response:

You have a couple of options. The most type-safe way would be to define C# classes which represent the schema of your JSON content and then deserialise into an instance of those like so:

public class Data
{
    public int Count { get; set; }
    public List<DataObject> Objects { get; set; }
}

public class DataObject
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Login { get; set; }
}

public class  MyJSONObject
{
    public bool HasError { get; set; }
    public string AlertType { get; set; }
    public string AlertMessage { get; set; }
    public Data Data { get; set; }
}

...

//Deserialise
var json = "<snip>";
var deserialised = JsonSerializer.Deserialize<MyJSONObject>(json);

//Extract the info you want
 Console.WriteLine(deserialised.Data.Objects[0].LastName);

A second, more quick and dirty way to do it would be to parse the JSON into a JsonObject (this is using System.Text.Json) and then extract out the info you need:

var jsonObj = JsonObject.Parse(Properties.Resources.JSON);
var objectsArray = ((JsonArray)y["Data"]["Objects"]);

Console.WriteLine(objectsArray[0]["LastName"]);

A similar method would work with Newtonsoft.Json as well, although you'd need to use JObject instead of JsonObject and JArray rather than JsonArray in that case.

CodePudding user response:

If you are using System.Text.Json:

var jsonObject= JsonSerializer.Deserialize<JsonObject>(jsonString);

Then you can use jsonObject["Data"]["Objects"][0]["FirstName"] to get the data.

  • Related