Sebastian
Sebastian

Reputation: 4811

Json newtonsoft : Deserialize string array from an Object

My JSON is a very long one and i am fetching only one section "parent_crumbs" from the long JSON

 ...................,
 "parent_crumbs":["Platforms","New platform"],
 "promise_by":"2016-08-01",
  ....

The code I used to fetch value of "parent_crumbs" is

  JObject lp_p = JObject.Parse(response_json);
  string val= lp_p["parent_crumbs"].ToString();

This returns the following value

 "[\r\n  \"Platforms\",\"New platform\"\r\n]"

Now I have to do a comparison with the first value from the array as the string is available in a Dictionary as key value and if available return ID

        Packages = new Dictionary<string, int>();
        Packages.Add("Platforms", 10212);
        Packages.Add("New platform", 10202);
        Packages.Add("Unknown platform", 10203);
        int category=

        if(Packages.ContainsKey(val))
        {
                Packages.TryGetValue(val, out category);
        }

So with current code I can't do the comparison straight away due to presence of [\r\n etc.

How to get the value as a string Array without special chars like [\r\n .

Making Model Classes for the JSON for deserialization is not preferred way for me. Since creating class is a big job for me as lot of properties are there in JSON and is dynamic of nature

Upvotes: 0

Views: 1925

Answers (3)

Mark
Mark

Reputation: 2071

you could also convert it to array with Linq

using System.Linq;

var tmp = lp_p["parent_crumbs"].Select(x => x.ToString());
foreach (var x in tmp)
{
    Console.WriteLine(x.ToString());
}

By using Select, it will help you convert it to array rather than to string

Upvotes: 2

SᴇM
SᴇM

Reputation: 7213

You can use DeserializeAnonymousType method for that:

var myType = new 
{ 
    parent_crumbs = new []{ "" }, 
    promise_by = default(DateTime) 
};

var result = JsonConvert.DeserializeAnonymousType(json, myType);

int category = 0;
string key = result.parent_crumbs[0];
if(Packages.ContainsKey(key))
{
    Packages.TryGetValue(key, out category);
}

References: DotNetFiddle Example, DeserializeAnonymousType

Upvotes: 0

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

We can use the below code

var input = "[\r\n  \"Platforms\",\"New platform\"\r\n]";
            var array =(JArray) JsonConvert.DeserializeObject(input);
            bool isEqual = array[0].Value<string>() == "Platforms";

Upvotes: 2

Related Questions