Saim Abdullah
Saim Abdullah

Reputation: 304

parsing dictionary of objects in c# Dictionary<string,object> data

I am passing following json in request body

{
  "areaId": "1",
  "cat": "2",
  "subcat": "41",
  "location": "1100",
  "sublocation": "11001",
  "briefDescription": "thissss is brief description",
  "detailedDescription": "this is detailed obj",
  "images": {
    "image1": "base64 string",
    "image2": "base64 string"
  }
}

and my handler looks like this

[HttpPost]
public HttpResponseMessage Post(Dictionary<string,object> data)
{
    int areaId = Int32.Parse(data["areaId"].ToString()); //this is how i am getting area from it 

    return Request.CreateResponse(HttpStatusCode.OK, new { some objects to return });
}

how can I extract the images from this json in a dictionary? and what will be the efficient way of doing this

Upvotes: 1

Views: 745

Answers (2)

Magnetron
Magnetron

Reputation: 8553

If you want to use the Linq to Json approach, you could do as follow:

JObject o = JObject.Parse(j);
Dictionary<string, string> images = new Dictionary<string, string>();
foreach(JProperty im in o["images"])
{
    images.Add(im.Name, (string)im.Value);
}

where j is a string containing your JSON.

Upvotes: 1

Fortega
Fortega

Reputation: 19682

As this is a JSON object, you could use a C# JSON Library, such as JSON.Net

You can use the 'Paste JSON as classes' functionality of Visual Studio to get the class structure:

public class Rootobject
{
    public string areaId { get; set; }
    public string cat { get; set; }
    public string subcat { get; set; }
    public string location { get; set; }
    public string sublocation { get; set; }
    public string briefDescription { get; set; }
    public string detailedDescription { get; set; }
    public Images images { get; set; }
}

public class Images
{
    public string image1 { get; set; }
    public string image2 { get; set; }
}

And then use the JsonConvert.DeserializeObject method to deserialize the json to a 'RootObject' instance

If you want to treat the images as a dictionary, the following structure should also work with json.net:

public class Rootobject
{
    public string areaId { get; set; }
    public string cat { get; set; }
    public string subcat { get; set; }
    public string location { get; set; }
    public string sublocation { get; set; }
    public string briefDescription { get; set; }
    public string detailedDescription { get; set; }
    public Dictionary<string, string> images { get; set; }
}

Check https://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm

Upvotes: 3

Related Questions