0

I'm newbie in asp.net c# . Iwant to show the json data into table with gridview .I have json data with this format :

[{
    "reviewerID": "A1YS9MDZP93857",
    "asin": "0006428320",
    "reviewerName": "John Taylor",
    "helpful": [
        0,
        0
    ],
    "reviewText": "last movement of sonata #6 is missing. What should one expect?",
    "overall": 3,
    "summary": "Parts missing",
    "unixReviewTime": 1394496000,
    "reviewTime": "03 11, 2014"
},
{
    "reviewerID": "A3TS466QBAWB9D",
    "asin": "0014072149",
    "reviewerName": "Silver Pencil",
    "helpful": [
        0,
        0
    ],
    "reviewText": "If you are a serious violin student on a budget, this edition has it all",
    "overall": 5,
    "summary": "Perform it with a friend, today!",
    "unixReviewTime": 1370476800,
    "reviewTime": "06 6, 2013"
}]

to show that into gridview I use the following code (using Json.net library)

JsonString = TextBox1.Text;
       dt = (DataTable)JsonConvert.DeserializeObject(JsonString, (typeof(DataTable)));
       GridView1.DataSource = dt;
       GridView1.DataBind();

the problem is gridview cannot show the data, and it's work if I remove "helpfull" attribute like this one by one :

{
"reviewerID": "A1YS9MDZP93857",
"asin": "0006428320",
"reviewerName": "John Taylor",
"reviewText": "The portfolio is fine except for the fact that the last movement of sonata #6 is missing. What should one expect?",
"overall": 3,
"summary": "Parts missing",
"unixReviewTime": 1394496000,
"reviewTime": "03 11, 2014"}

I don't know code how to remove it , Since i have large json data, i'ts difficult and wasting time to remove it manually. Any idea?

Ana
  • 113
  • 13
  • Why dont you convert it on js side? it would be much easier – iamawebgeek Jun 18 '15 at 07:42
  • thanks.Actually I just tried using many online json tool, but it's just allow me to remove it one by one, and another remove algrthm i've used , it's work, but not for multivalue attribute – Ana Jun 18 '15 at 07:49

1 Answers1

0

As you are using Json.NET, if you want to remove unwanted properties before deserializing to DataTable, you can convert to an intermediate LINQ to JSON JToken hierarchical representation, then remove properties with unwanted names. After this is done, you can deserialize to your final DataTable class with JToken.ToObject<T>.

To parse to a JToken, do:

        var obj = JToken.Parse(JsonString);

Then to remove unwanted properties by name:

        var unwanteds = new HashSet<string>(new[] 
        {
            "helpful"
        });
        foreach (var property in obj.Children().SelectMany(o => o.OfType<JProperty>()).Where(p => unwanteds.Contains(p.Name)).ToList())
        {
            property.Remove();
        }

Or, to remove all except wanted properties, by name:

        var keepers = new HashSet<string>(new[]
        {
            "reviewerID",
            "asin",
            "reviewerName",
            "reviewText",
            "overall",
            "summary",
            "unixReviewTime",
            "reviewTime",
        });
        foreach (var property in obj.Children().SelectMany(o => o.OfType<JProperty>()).Where(p => !keepers.Contains(p.Name)).ToList())
        {
            property.Remove();
        }

Finally, deserialize:

        var dt = obj.ToObject<DataTable>();
dbc
  • 104,963
  • 20
  • 228
  • 340
  • Hi @dbc , thanks for the answer, can u tell me what did obj.SelectTokens("[*]") – Ana Jun 19 '15 at 06:37
  • @Ana - it lets you do wildcard searches. See [Querying JSON with JSONPath](http://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) and [JSONPath - XPath for JSON](http://goessner.net/articles/JsonPath/). – dbc Jun 19 '15 at 06:45
  • can u tell me parameter in this method : `obj.SelectTokens("[*]")` , I have tried the source code you gave (remove all except wanted properties), when run occurred exception : An exception of type 'Newtonsoft.Json.JsonException' occurred in Newtonsoft.Json.dll but was not handled in user code Additional information: Unexpected character while parsing path indexer: * – Ana Jun 19 '15 at 06:45
  • @Ana - what version of Json.NET are you using? JSONPath support was added to [6.0 Release 1](http://james.newtonking.com/archive/2014/02/01/json-net-6-0-release-1-%E2%80%93-jsonpath-and-f-support). – dbc Jun 19 '15 at 06:46
  • Whoa, I use Json.NET 5.0.6, I should update it first,. – Ana Jun 19 '15 at 06:52
  • @Ana - you might want to, there are probably bugs that have been fixed. I can update the answer though. – dbc Jun 19 '15 at 06:57
  • @Ana - [`Children()`](http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JContainer_Children.htm) should do the same thing given that the root container is an array. Answer updated. – dbc Jun 19 '15 at 07:00
  • yeah @dbc, after update json.net now new exception occured for Binding data to gridview ` var dt = obj.ToObject(); GridView1.DataSource = dt; GridView1.DataBind();` An exception of type 'System.InvalidOperationException' occurred in System.Web.dll but was not handled in user code Additional information: The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content. – Ana Jun 19 '15 at 07:09
  • @Ana - Maybe I misunderstood your precise problem -- did you want to remove the `helpful` property, or remove *all except* the `helpful` property? In my answer I remove everything except `helpful`. – dbc Jun 19 '15 at 07:12
  • yes i need to remove helpful property (also it's value), please help – Ana Jun 19 '15 at 07:16
  • @Ana - answer updated by exchanging the contents of `unwanteds` and `keepers` – dbc Jun 19 '15 at 07:19
  • Thank you very much for the help, now it's works :) , Thanks – Ana Jun 19 '15 at 07:23