Alon Shmiel
Alon Shmiel

Reputation: 7121

How to get some values from a JSON string in C#?

I have a string and I want to get some values from it.

My strings seem like:

string1:

"{\r\n   \"id\": \"100000280905615\",
 \r\n \"name\": \"Jerard Jones\",
 \r\n   \"first_name\": \"Jerard\",
 \r\n   \"last_name\": \"Jones\",
 \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\",
 \r\n   \"username\": \"Jerard.Jones\",
 \r\n   \"gender\": \"female\",
 \r\n   \"locale\": \"en_US\"\r\n}"

string2:

"{\r\n   \"id\": \"100000390001929\",
  \r\n   \"name\": \"\\u05d1\\u05d2\\u05e8\\u15dc\\u25d9 \\u05d1\\u05e8\\u05d5\\u05e9\",
  \r\n   \"first_name\": \"\\u05d4\\u05d2\\u05e7\\u02dc\\u05d9\",
  \r\n   \"last_name\": \"\\u05d1\\u05e8\\u05d5\\u05e9\",
  \r\n   \"link\": "https://www.facebook.com/people/\\u05d2\\u05d1\\u05e@\\u05dc\\u05d9-\\u05d1\\u05e8\\u05d4\\u05e9/100000390001929\",
  \r\n   \"gender\": \"female\",
  \r\n   \"locale\": \"he_IL\"\r\n}"

Unfortunately, there is a situation that a string will be by the same concept, but without some parameters:

string3:

"{\r\n   \"id\": \"100000390001929\",
  \r\n   \"last_name\": \"\\u05d1\\u05e8\\u05d5\\u05e9\",
  \r\n   \"gender\": \"female\",
  \r\n   \"locale\": \"he_IL\"\r\n}"

How can I get the values of: id, first_name, last_name, gender, locale?

Upvotes: 108

Views: 338772

Answers (7)

Pooja Parmar
Pooja Parmar

Reputation: 133

This code is working for us:

string json = "{\"subjectId\":\"d7aa0fdf-df51-4ef7-ad0b-9ace314b5ppb\"}";
dynamic data = JObject.Parse(json);
string userId = data["subjectId"];

Upvotes: 3

Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29231

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Upvotes: 181

Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29231

You can also use this alternative specifying the expected type:

using Newtonsoft.Json;

class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

string jsonString = "{\"name\": \"John\", \"age\": 30}";

Person person = JsonConvert.DeserializeObject<Person>(jsonString);

Upvotes: 3

Stefan
Stefan

Reputation: 17648

A .NET 6 version using System.Text.Json

using System;
                    
public class Program
{
    public static void Main()
    {
        var jsonString = @"{ ""id"" : 123 }";
        
        //parse it
        var yourObject = System.Text.Json.JsonDocument.Parse(jsonString);
        //retrieve the value
        var id= yourObject.RootElement
                          .GetProperty("id");
        
        Console.WriteLine(id);
    }
}

To retrieve nested properties, you can chain the GetProperty calls. As a more advanced example:

//access first element of array "persons" get nested property "age" 
var age = yourObject.rootElement.GetProperty("persons")[0]
                                .GetProperty("age");

Upvotes: 29

Muhammad Awais
Muhammad Awais

Reputation: 4492

Following code is working for me.

Usings:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

Code:

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}

Upvotes: 31

DKR
DKR

Reputation: 5734

my string

var obj = {"Status":0,"Data":{"guid":"","invitationGuid":"","entityGuid":"387E22AD69-4910-430C-AC16-8044EE4A6B24443545DD"},"Extension":null}

Following code to get guid:

var userObj = JObject.Parse(obj);
var userGuid = Convert.ToString(userObj["Data"]["guid"]);

Upvotes: 24

Ligabb
Ligabb

Reputation: 126

Create a class like this:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

Then create JSonSerializer:

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

and deserialize object:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}

Upvotes: 10

Related Questions