How to remove remove key value from JSON using C# - c#

I have a json response that I will need to edit before binding to a GridView. I'm using Newtonsoft JSON library. The data binds perfectly to the GridView when "values" are removed from the string. When values is added to the json response I get this error message.
Message=Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
How can I remove "values" from jsonResponse before binding to GridView?
<asp:GridView ID="gvJson" runat="server" BackColor="White" BorderColor="#3399ff"
BorderStyle="Dotted" BorderWidth="1px" CellPadding="3" GridLines="Both" AutoGenerateColumns="true"></asp:GridView>
var jsonResponse = "{\"values\":[{\"id\":\"201\",\"name\":\"Zack\"},{\"id\":\"158\",\"name\":\"Kim\"},{\"id\":\"254\",\"name\":\"Scott\"}]}";
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(jsonResponse);
gvJson.DataSource = dataTable;
gvJson.DataBind();
My JSON:
{
"values": [
{
"id": "201",
"name": "Zack"
},
{
"id": "158",
"name": "Kim"
},
{
"id": "254",
"name": "Scott"
}
]
}

There are a couple of ways to do this..
You could use JObject
var dataTable = JObject
.Parse(jsonResponse)["values"]
.ToObject<DataTable>();
Or as been suggested, fully deserialize the Json to concrete classes and bind the array to control directly
Given
public class Value
{
public string id { get; set; }
public string name { get; set; }
}
public class Root
{
public List<Value> values { get; set; }
}
Usage
var root = JsonConvert.DeserializeObject<Root>(jsonResponse);
// your Data , root.Data

Instead of removing the values from JSON response, you should be able to do something like
var jsonObject = JObject.Parse(jsonResponse);
var dataTable = JsonConvert.DeserializeObject<DataTable>(jsonObject["values"].ToString());
gvJson.DataSource = dataTable;
gvJson.DataBind();

Related

Created Nested JSON array from JSON array

I am pretty new to JSON and C# and have created an Azure Function that ties back to Snowflake which requires a very specific type of JSON response. I would like assistance if any in turning a JSON response I'm getting to a slightly different formatted response.
{
"access_token": "access token value here" , "user": "user_val"
}
to looking like
{
"data":
[
[ 0, { "access_token" : "access token value here", "user" : "user_val" } ]
]
}
I need create a nested array with "data" as the parent and a row number response starting at 0.
Using Json.NET:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string json = #"{
""access_token"": ""access token value here"" , ""user"": ""user_val""
}";
Access a = JsonConvert.DeserializeObject<Access>(json);
var accessCollection = new AccessCollection
{
Data = new List<Access> { a }
};
json = JsonConvert.SerializeObject(accessCollection, Formatting.Indented);
Console.WriteLine(json);
}
}
public class Access
{
[JsonProperty("access_token")]
public string AccessToken
{
get;
set;
}
[JsonProperty("user")]
public string User
{
get;
set;
}
}
public class AccessCollection
{
[JsonProperty("data")]
public List<Access> Data
{
get;
set;
}
}
In addition, I consider the inner array is not usual because the data type are int and object. In general, they should be of same type. Because of that, I use a single dimensional array instead.
Please modify the codes according to situation.
.NET Fiddle

How can I print Json values in a gridview?

I am trying to print values from a Json string in a gridview with C# using Visual Studio 2017. The problem is that I can't get the specific Value to a single word.
Here is my code:
string link = #"http://alexander.*************/test.php";
string json = new WebClient().DownloadString(link);
JObject jObject = JObject.Parse(json);
I want to print both Values from "Name" in the gridview, but how?
The Names has to put in this Item list:
myItems = (array?);
string test2 = test1.ToString(Formatting.Indented);
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, myItems);
GridviewCoins.Adapter = adapter;
And finally the json string is:
{
"Coins": [[{
"Name": "007",
"Id": "5294",
}], [{
"Name": "1337",
"Id": "20824",
}
There is a couple problems here, first is that your Coins Property is an array of arrays, and that you jsonObject is not complete it should look like :
"{ "Coins": [[{ "Name": "007", "Id": "5294", } ], [{ "Name": "1337", "Id": "20824", }]]}";
That said if this is a copy paste error I would do some thing like:
public IEnumerable<Coin> GetCoins(string json)
{
var jObject = JObject.Parse(json);
var coinPropery = jObject["Coins"] as JArray;
var coins = new List<Coin>();
foreach (var property in coinPropery)
{
var propertyList = JsonConvert.DeserializeObject<List<Coin>>(property.ToString());
coins.AddRange(propertyList);
}
return coins;
}
and the coin object:
public class Coin
{
public int Id { get; set; }
public string Name { get; set; }
}
when then you have a c# object and you can do what ever you want with it.
EDIT:
You can add to gridview by following Click here

Deserialize JSON value without name

How can I deserialize a string in C# that only have values and no name. It looks like this: The problem is that this stream of string does not have name and uses array.
{
"result": {
"14400": [
[
1502985600,
262.18,
262.18,
257,
257,
1096.0131
],
[
1503000000,
257,
261.33,
254.8,
257,
1130.5897
]
],
"14405": [
[
1503014400,
258.03,
261.5,
257.01,
257.01,
520.7805
],
[
1503028800,
258,
260.98,
252.4,
259.56,
298.5658
],
]
]
}
}
Just create a class like
public class Root
{
public Dictionary<int,List<List<double>>> Result { get; set; }
}
and deserialize as
var res = JsonConvert.DeserializeObject<Root>(json);
I see it's an array, you could create a method to parse the class out of given JArray.
The Jason data
public void methpod()
{
string json ="Your jason value "
var factory = new Factory();
var suggest = factory.Create(json);
Console.WriteLine(suggest);
}
Make a class as suggested :
public class Factory
{
public Evan Create(string json)
{
var array = JArray.Parse(json);
string search = array[0].ToString();
string[] terms = array[1].ToArray().Select(item => item.ToString()).ToArray();
return new Evan{Search = search, Terms = terms};
}
}
and another
public class Evan
{
public string Search { get; set; }
public IEnumerable<string> Terms { get; set; }
public override string ToString()
{
return string.Format("Search={0},Terms=[{1}]",
Search, string.Join(",", Terms));
}
}
Tip
If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, Visual Studio 2019 can automatically generate the class you need:
Copy the JSON that you need to deserialize.
Create a class file and delete the template code.
Choose Edit > Paste Special > Paste JSON as Classes.
The result is a class that you can use for your deserialization target

Deserialize a nested DataSet from Json String with Json.NET

I try to deserialize a DataSet from a JSON String with Json.NET. The Json String contents a status, message and the table that I want to use:
{
"status": "ok",
"message": "",
"table": [{
"column1": "value1",
"column2": "value2"
}, {
"column1": "value3",
"column2": "value4"
}]
}
Here my source:
public class RequestResult
{
public string status { get; set; }
public string message { get; set; }
}
...
var serializer = new JsonSerializer();
var sr = new StreamReader(response.GetResponseStream()).ReadToEnd();
var rr = JsonConvert.DeserializeObject<RequestResult>(sr);
// Without status and message the following works fine like here:
// http://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(sr);
gridControlMain.DataSource = dataSet.Tables["table"];
If I use the Json String without status and message it works fine, but I need status and message! Exception message from Json.NET is:
Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path 'status', line 1, position 14.
How can I manage that?
Best regards
Your snippet shows an object with three properties, status, message and table. This object can't be deserialized as a DataTable. The table property can.
You can deserialize this snippet to a class with two string and one DataTable property, eg:
class MyTableUtilClass
{
public string Status{get;set;}
public string Message {get;set;}
public DataTable Table{get;set;}
}
var myUtil=JsonConvert.DeserializeObject<MyTableUtilClass>(jsonText);
DataTable myTable=myUtil.Table;

Convert a .Net object to JSON

From a web service method I am returning an object of type 'GridBindingDataSet'. But its not getting serialized as JSON automatically.
Is there some way of making sure that the object gets serialized as JSON? I am using AJAX enabled web service that can be called from client-side using jQuery.
public class GridBindingDataSet
{
public int TotalCount { get; set; }
public DataTable Data { get; set; }
}
EDIT 1:
I am getting the following error when the web service method is called from jQuery:
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'
EDIT 2:
I used JSON.net to serialize the above object of GridBindingDataSet. The web service is now returning a string rather than a GridBindingObject. Code for this is as below. But the browser cannot understand d.TotalCount and d.Data even though they are there in JSON returned.
[WebMethod]
public string GetJSONDataSetForGrid()
{
...
...
DataTable dt = GetDataForPage0();
int total = GetTotalCount();
GridBindingDataSet gridBindingData = new GridBindingDataSet ( total, dt);
//return a JSON serialized string
return JsonConvert.SerializeObject(gridBindingData,
Formatting.None, new JsonSerializerSettings
{
PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None
});
}
But the JSON being returned is full of back slashes which the browser is not interpreting since the grid using the JSON string is showing up as empty. d.Data and d.TotalCount are not being parsed from the JSON string.
JSON retuned is as below:
{"d":"{\"TotalCount\":81,\"Data\":[{\"ProductName\":\"Alice Mutton\",\"UnitPrice\":39.00,
\"UnitsInStock\":0,\"Discontinued\":true},{\"ProductName\":\"Aniseed Syrup\",\"UnitPrice\":10.00,
\"UnitsInStock\":13,\"Discontinued\":false}]}"}
Also its worth having a look at Json.Net, many would say one of the best Json serializers available, I use it for all of my projects.
In response to the circular referece have a look at preserving references in the documentation, from their examples:
Directory root = new Directory { Name = "Root" };
Directory documents = new Directory { Name = "My Documents", Parent = root };
File file = new File { Name = "ImportantLegalDocument.docx", Parent = documents };
documents.Files = new List<File> { file };
string preserveReferenacesObjects = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
// {
// "$id": "1",
// "Name": "My Documents",
// "Parent": {
// "$id": "2",
// "Name": "Root",
// "Parent": null,
// "Files": null
// },
// "Files": [
// {
// "$id": "3",
// "Name": "ImportantLegalDocument.docx",
// "Parent": {
// "$ref": "1"
// }
// }
// ]
// }

Categories

Resources