read data from a json formatted object - json

I have a .net application in which I am getting a response data in json format. I have used the below code to get the json response.
string details= new System.Net.WebClient().DownloadString(url);
var temp = JsonConvert.DeserializeObject(details.ToString());
I have got a json format object in temp and json format string in details
I am getting an output as below from temp
{"data":
[
{"category":"Community","name":"New Page","access_token":"accesstoken_data1","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"1234"},
{"category":"Community","name":"Page ABC","access_token":"accesstoken_data2","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"56789"}
]
,"paging":{"next":"https:\/\/graph.facebook.com\/1100234567\/accounts?access_token=pageAccesstoken&limit=5000&offset=5000&__after_id=77786543"}
}
I need to get the category,name,access_token as key and corresponding data as values in some dictionary.
How can I achieve it?

Hope this will do the required stuffs
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
This was taken from the following link
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
string json = #"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>
More examples: Serializing Collections with Json.NET

Related

Convert JSON response of LinkedHashmap List to Custom Java Response object

I came across a weird scenario.
I was calling a External API which is returning Lists of LinkedHashMap (E.g: List<LinkedHashMap<String, String>)
So the question is how to convert this JSON response to Custom Response object in Java
Use the below code to convert JSON response to Custom Response object in Java.
ResponseEntity<Object> response = restTemplate.exchange(
pathURL,
HttpMethod.{GET/POST ..},
createHeader(),
Object.class
);
final List<LinkedHashMap> responseList = objectMapper
.convertValue(
response.getBody(),
new TypeReference<List<LinkedHashMap>>() {
}
);
LinkedHashMap<String, String> responseMap = responseList.get(0);
CustomResponseObj infoResp = objectMapper.convertValue(responseMap, CustomResponseObj.class);
private HttpEntity<?> createHeader() {
HttpHeaders headers = new HttpHeaders();
return new HttpEntity<>(headers);
}

Deserializing Json String which is stored in a string variable

I am working in VS 2015 and c#.
I have a Json String which has a list of collections, each collection represents an object,
string wsjson =
"{
"customAttributes":
[{"description":"xxxxxxx","id":11,"value":"xxxxxxx"},{"description":"xxxxxxx","id":10,"value":"xxxxxxx"}],
"location":{"account":"xxxxxxx","cabinet":"xxxxxxx"},
"misc":{"approved":false,"archived":false,"deleted":false,"echo":true,"external":false,"favorite":false,"officialLocked":false,"signed":false},
"permissions":[{"xxxxxxx":true,"xxxxxxx":false,"edit":true,"noAccess":false,"share":true,"view":true}],
"standardAttributes":{"aclStatus":"xxxxxxx","created":"\/Date(xxxxxxx)\/","createdBy":"xxxxxxx","createdByGuid":"xxxxxxx","envId":"xxxxxxx","extension":"ndws","id":"xxxxxxx","modified":"\/Date(xxxxxxx)\/","modifiedBy":"xxxxxxx","modifiedByGuid":"xxxxxxx","name":"xxxxxxx","officialVer":1,"size":4,"syncMod":xxxxxxx,"url":"xxxxxxx","versions":1}}"
DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
I am getting an error. I tried to follow this (Deserializing Json String into multiple Object types) solution but I am getting error for this line as my jason data is in a string and no function to parse string.
var j = JArray.Parse(data);
Here is the visual image of the jason data.
Actual code block in my program is:
foreach (DataRow row in dataTable.Rows)
{
string wsjson = GetWorkspaceProfile(row[0].ToString());
DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
DataTable wsdataTable = wsdataSet.Tables["standardAttributes"];
foreach (DataRow wsrow in wsdataTable.Rows)
{
cmbWorkspaceByCabinet.Items.Add(new KeyValuePair<string, string>(row["envId"].ToString(), wsrow["name"].ToString()));
}
}
Where GetWorkspaceProfile is a string type return function which return me JSON data as string like the image above.
public string GetWorkspaceProfile(string WorkspaceId)
{
string responseStr = "";
string url = "v1/Workspace/" + WorkspaceId + "/info";
RestType type = RestType.GET;
Boolean useXml = false;
RestRequest rr = FormRequest(type, url, useXml);
IRestResponse response;
try
{
response = executeRequest(rr);
responseStr = response.Content;
}
catch (Exception ex)
{
return null;
}
return responseStr;
}
JArray.Parse will not work, because you don't have a json array, it is an object. Also not the all values of that object are collections, for example location is also object, not a collection. You have some options to parse it
Parse root object into Dictionary
JsonConvert.DeserializeObject<Dictionary<string, string>>(wsjson)
then parse every value of the dictionary to array if value is array and to dictionary if value is object.
Create a C# class according to your json data and parse string directly into instance of that class
JsonConvert.DeserializeObject<JsonModel>(wsjson);
where JsonModel is the class you need to create.
You can use JArray and JToken to get the values you want using json path.

DataTable to JSON string for amcharts

I have a method in my model that queries my SQL Server database and stores the results in a datatable. Then, I am using the following method to convert that datatable into a JSON string.
public void ConvertDataTabletoJSONString(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
JSONstring = serializer.Serialize(rows);
}
My controller looks like this:
public ActionResult getMonthlyData()
{
TDR_Monthly viewModel = new TDR_Monthly();
viewModel.getList(0);
return Json(viewModel.JSONstring, JsonRequestBehavior.AllowGet);
}
My view's javascript AmCharts.makechart dataLoader has this:
"dataLoader":
{
"url": "../TDR_MonthlyController/getMonthlyData",
"format": "json"
}
When I "test" the output of that string (by displaying the string's contents in my view, it shows properly in the browser, like so:
[{"REGION":"Atlanta", "STATE_NAME":"Alabama", "STATE":"AL", "CATEGORY_ID":"0 ", "CATEGORY":"No Group", "COUNT":100, "DEFICIENCY1":0, "DEFICIENCY2":0, "RESCIND1":0, "RESCIND2":0}]
However, when I modify the browser's URL to execute the JSON call (http://localhost:49777/Monthly/getMonthlyData) and I open the JSON file, it looks like it has a crap tone of extra spacing and characters:
"[{\"REGION\":\"Atlanta \",\"STATE_NAME\":\"Alabama \",\"STATE\":\"AL\",\"CATEGORY_ID\":\"0 \",\"CATEGORY\":\"No Group \",\"COUNT\":100,\"DEFICIENCY1\":0,\"DEFICIENCY2\":0,\"RESCIND1\":0,\"RESCIND2\":0}]
The view itself informs me that it cannot parse it
Error parsing JSON file: ../TDR_MonthlyController/getMonthlyData
Any help would be appreciated!!!
In getMontlhyData, try changing
return Json(viewModel.JSONstring);
to
return Content(viewModel.JSONstring, "application/json");
because you already have a JSON string. The Json() method is serializing it again.

Converting associative array request parameters to JSON with Jackson

I am the recipient of a webhook POST that looks like this, which I have decoded for readability.
id=12345&event=this_event&payload[customer][name]=ABC Company&payload[customer][city]=New York&payload[service][name]=New Customer&payload[service][action]=New
Using Spring MVC, I can easily get this into a Map<String, Sting> that looks like this
{id=97659204, event=test, payload[customer][name]=ABC Company, payload[customer][city]=New York, payload[service][name]=New Customer, payload[service][action]=New}
I need to parse every parameter (or Map key) that starts with "payload" into a JSON object.
My desired output from parsing the request parameters that start with "payload" would look something like this
{
customer : {
name : "ABC Company",
city : "New York"
},
service : {
name : "New Customer",
action : "New"
}
}
With the final state being a call to Jackson's ObjectMapper to turn that JSON into a POJO.
Since I have no control over the data format begin sent to me, what is the best/correct option for parsing those request parameters into a JSON object?
Thanks.
I ended up writing a custom parser for the payload[][][] parameters being passed in. It uses regex matcher and then recursion to analyze each parameter, traverse a Map of 1...n Maps and then the resulting Map makes perfect JSON.
#RequestMapping(value = "/receiver", method = RequestMethod.POST)
#ResponseBody
public void receiver(#RequestParam Map<String, Object> requestBody) throws IOException {
Pattern pattern = Pattern.compile("\\[([^\\]]+)]");
Map<String, Object> payloadMap = new HashMap<>();
Matcher matcher = null;
List<String> levels = null;
for (String key : requestBody.keySet()) {
if (key.startsWith("payload")) {
matcher = pattern.matcher(key);
levels = new ArrayList<>();
while (matcher.find()) {
levels.add(matcher.group(1));
}
payloadMap = nestMap(payloadMap, levels.iterator(), (String) requestBody.get(key));
}
}
LOG.debug(mapper.writeValueAsString(payloadMap));
}
#SuppressWarnings("unchecked")
private Map<String, Object> nestMap(Map<String, Object> baseMap, Iterator<String> levels, String value) {
String key = levels.next();
if (!levels.hasNext()) {
baseMap.put(key, value);
} else {
if (!baseMap.containsKey(key)) {
baseMap.put(key, nestMap(new HashMap<String, Object>(), levels, value));
} else {
baseMap.put(key, nestMap((Map<String, Object>) baseMap.get(key), levels, value));
}
}
return baseMap;
}

GWT HashMap to/from JSON

I might be getting a bit tired tonight but here it goes:
I'd like to have GWT HashMap to/from JSON. How would I achieve this?
In other words, I'd like to take an HashMap, take its JSON representation, store it somewhere and get it back to its native Java representation.
Here is my quick solution:
public static String toJson(Map<String, String> map) {
String json = "";
if (map != null && !map.isEmpty()) {
JSONObject jsonObj = new JSONObject();
for (Map.Entry<String, String> entry: map.entrySet()) {
jsonObj.put(entry.getKey(), new JSONString(entry.getValue()));
}
json = jsonObj.toString();
}
return json;
}
public static Map<String, String> toMap(String jsonStr) {
Map<String, String> map = new HashMap<String, String>();
JSONValue parsed = JSONParser.parseStrict(jsonStr);
JSONObject jsonObj = parsed.isObject();
if (jsonObj != null) {
for (String key : jsonObj.keySet()) {
map.put(key, jsonObj.get(key).isString().stringValue());
}
}
return map;
}
Not the most optimized, but should be easy to code: use JSONObject.
Iterate over your map's entries and put them in a JSONObject (converting each value to a JSONValue of the appropriate type), then call toString to get the JSON representation.
For parsing, get a JSONObject back using a JSONParser, then iterate over the keySet, geting the values and putting them in your map (after unwrapping the JSONValues)
But beware of the keys you use! You cannot use any kind of key as a property name in JS; and JSON processing in the browser always involve going through a JS object (or implementing the JSON parser yourself, which won't perform the same)