-1

I have a JSON string that I don't want to completely deserialize. I only want to deserialize the content within' the JSON string.

This is how a string can look like:

"{\"content\":{\"token\":\"*************************\",\"is_verified\":1,\"account_id\":45087,\"is_starter\":0,\"days_left\":1},\"status\":200,\"id\":\"test\",\"method\":\"accounts_login\"}"

I only need the content object. So I need to make a Regex(?) that can make this string into:

"{\"token\":\"*************************\",\"is_verified\":1,\"account_id\":45087,\"is_starter\":0,\"days_left\":1}"

What would be the best way to do this?

Jelmer
  • 949
  • 3
  • 10
  • 23

2 Answers2

0

You can do this with Newtonsoft.Json as simple as

var json = "{\'content\':{\'token\':\'*************************\',\'is_verified\':1,\'account_id\':45087,\'is_starter\':0,\'days_left\':1},\'status\':200,\'id\':\'test\',\'method\':\'accounts_login\'}";

var jToken = JToken.Parse(json);
var contentToken = jToken["content"]; //This selects the Json-Node
var content = contentToken.ToObject<YourContentClass>();
Mueui
  • 181
  • 8
0

From my opinion, the best approach is to deserialize the whole JSON-string on Data-Layer level. And, after deserializing to an object, select the data you need from the object in another layer: Business Layer.

How to deserialize a JSON-string to an object is explained in this topic: Deserialize JSON with C#

public class Rootobject
    {
        public Content content { get; set; }
        public int status { get; set; }
        public string id { get; set; }
        public string method { get; set; }
    }

    public class Content
    {
        public string token { get; set; }
        public int is_verified { get; set; }
        public int account_id { get; set; }
        public int is_starter { get; set; }
        public int days_left { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string json =
                "{\"content\":{\"token\":\"*************************\",\"is_verified\":1,\"account_id\":45087,\"is_starter\":0,\"days_left\":1},\"status\":200,\"id\":\"test\",\"method\":\"accounts_login\"}";

            Rootobject rootobject = new JavaScriptSerializer().Deserialize<Rootobject>(json);

            Content content = rootobject.content; // Select what you need

            System.Console.ReadKey();
        }
    }
Jordy
  • 661
  • 7
  • 26