Deserializing Json String which is stored in a string variable - json

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.

Related

JSON parsing in C# - extract a string array to another array

I have a JSON string returned from an API and it has 1 field - ApiErrorMessage and an array - BlogCategoryList
entry = "{\"ApiErrorMessage\":null,\"BlogCategoryList\":
[{\"BlogCategoryId\":2,\"BlogCategoryDescr\":\"To Start\"},
{\"BlogCategoryId\":1,\"BlogCategoryDescr\":\"Introduction\"},
{\"BlogCategoryId\":1,\"BlogCategoryDescr\":\"Introduction\"}]}"
In need to extract out that JSON string array to a variable that just has that JSON string array (it should look like below). As as I need to pass it along to be deserialized.
{"BlogCategoryList":
[{"BlogCategoryId":2,"BlogCategoryDescr":"To Start"},
{"BlogCategoryId":1,"BlogCategoryDescr":"Introduction"},
{"BlogCategoryId":1,"BlogCategoryDescr":"Introduction"}]
}
public class BlogCategoryResult
{
public BlogCategoryResult()
{
this.BlogCategoryList = new List<BlogCategory>();
}
public string ApiErrorMessage { get; set; }
public List<BlogCategory> BlogCategoryList { get; set; }
}
My code. Just not sure how to extract it.
// Note: entry is a string type.
var entry = result.Content.ReadAsStringAsync().Result;
// I tried this, but the result is not correct.
string[] resultArray = entry.Split('[');
// I tried this, I get the list but then I get 'Can not convert Array to String' on the last command where I do the cast.
JObject o = JObject.Parse(entry);
string name = (string)o["ApiErrorMessage"];
JArray list = (JArray)o["BlogCategoryList"];
string listofentries = (string)list;
// Deserializing the response (just the list) received from web api and storing into a model.
blogCategoryResult.BlogCategoryList = JsonConvert.DeserializeObject<List<BlogCategory>>
(listofentries);
I think that you should deserialize the entire json by passing the BlogCategoryResult class between the < and > of JsonConvert.DeserializeObject, and the whole entry variable in the ( and ), after that you can easily pick the BlogCategoryList property
var entry = result.Content.ReadAsStringAsync().Result;
blogCategoryResult.BlogCategoryList = JsonConvert
.DeserializeObject<BlogCategoryResult>(entry)
.BlogCategoryList;

How to access nested JSON with array in firebase

I want to access a JSON of this structure in firebase
The structure
{
"questions":{
"English":{
"English_2002":[
{
"correct_ans":"A",
"OptionA":"a coder",
"OptionB":"a hacker",
"OptionC":"a writer",
"OptionD":"a programmer",
"Question":"Who build software"
},
{},
{}
],
"English_2003":[],
}
}
}
I want this structure. In the subject structure, other subjects will come after I exhaust 9 years of English.
My confusion is how to logically get each subject since firebase will only accept the root name questions.
Please I may sound dumb, but I have a very long questions thread almost 55000 lines. Because firebase accept one JSON tree.
Sorry i wasn't very clear i was asking from the stack phone app:
I have a question json tag of the structure above; my question is how will i be able to access the object subject like "english":{
// then accessing the first english array "english":[]
//since am now using firebase.
}
initially each array was individual json file, i have to recreate them into one for firebase sake. this is how i was parsing it then.
public class QuestionParser {
Context context;
public QuestionParser(Context c) {
this.context = c;
}
public ArrayList<Question> getJsonFromUrl(String url, String arrayName)
{
ArrayList<Question> arrayofQuestion = new ArrayList<>();
return arrayofQuestion;
}
// Processing question from JSon file in res > raw folder
public ArrayList<Question> parseQuestionJson(int rawJsonFileId, String arrayName) {
ArrayList<Question> questionList = new ArrayList<>();
String jsonstr = null;
try {
InputStream in = context.getResources().openRawResource(rawJsonFileId);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
jsonstr = sb.toString();
Log.d("REEEEADDD" + this.toString(), jsonstr);
//System.out.println(jsonstr);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(jsonstr)) {
return null;
}
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray jsonArray = jsonObject.getJSONArray(arrayName);
JSONObject jobject;
for (int i = 0; i < jsonArray.length(); i++) {
// TEST
jobject = jsonArray.getJSONObject(i);
String ans = jobject.getString("correct_answer");
String graphic_name = jobject.getString("question_image");
String optionA = jobject.getString("optiona");
String optionB = jobject.getString("optionb");
String optionC = jobject.getString("optionc");
String optionD = jobject.getString("optiond");
String questionNo = jobject.getString("question_number");
String question = jobject.getString("question");
questionList.add(new Question(questionNo, graphic_name, question, optionA, optionB, optionC, optionD, ans));
Log.d("DDD" + this.toString(), String.valueOf(questionList.get(i)));
}
Log.i("ONE QUESTION", questionList.get(50).getQuestion());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return questionList;
}
}
So how can i parse it from firebase because initially, if a student chooses question and year i passes those value as parameter and use them for parsing. but in firebase now i have access to only root firebase name in the get reference e method
To access for example "correct_ans":"A" you would query your firebase like so:
your.firebase.domain/questions/English/English_2002/0/correct_ans
Notice that each level in the json object is represented by a / and the key you want to access whereas in case of an array you simple add the array index. JSON's simple structure also allows simple REST like access

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.

read data from a json formatted object

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

Cannot deserialize xml string with Newtonsoft.Json.JsonConvert.DeserializeObject

Hi I am passing an xml as string
<AbcDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Abc">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>
When I am trying creating Custom Model Binder for Web Api
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(json))
{
var jsonObject = (JObject) Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
The json string passing as an parameter to the below method is an xml as string
I am facing exception at Newtonsoft.Json.JsonConvert.DeserializeObject(json);
Exception Details:
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
You are getting an error because JsonConvert.DeserializeObject() expects JSON input, not XML. If you want to handle XML with a JObject, you'll need to convert the XML to JSON first. The JsonConvert class has a SerializeXmlNode() method for this purpose.
Demo:
class Program
{
static void Main(string[] args)
{
string json = #"
<AbcDto xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Abc"">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>";
// If the json string contains XML, convert it to JSON
if (json.TrimStart().StartsWith("<"))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(json);
json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
}
// Now you can load the JSON into a JObject
var jsonObject = JObject.Parse(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
foreach (string name in jsonPropertyNames)
{
Console.WriteLine(name);
}
}
}
Output:
#xmlns:i
#xmlns
Id
Description
Name
PolicyId
Status
TimeZoneId