我在请求正文中传递了json
{
"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"
}
}
我的处理程序看起来像这样
[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 });
}
如何在字典中从这个json中提取图像?什么是有效的方式
答案 0 :(得分:2)
由于这是一个JSON对象,您可以使用C#JSON库,例如JSON.Net
您可以使用Visual Studio的“粘贴JSON作为类”功能来获取类结构:
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; }
}
然后使用JsonConvert.DeserializeObject
方法将json反序列化为“RootObject”实例
如果您想将图像视为字典,以下结构也适用于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; }
}
检查https://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm
答案 1 :(得分:1)
如果您想使用Linq to Json方法,可以按照以下步骤操作:
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);
}
其中j
是包含您的JSON的字符串。