1

How can I convert my json-string to class

this is my json

{
    "$id": "1",
    "Result": {
        "$id": "2",
        "dateTime": 23821964,
        "list": [{
            "$id": "3",
            "UserId": 302,
            "UID": "302_UID",
            "Title": "شیدکو",
            "Sender": "شیدکو",
            "Answer": "",
            "Comment": "test 2",
            "ProductTitle": null,
            "CommentId": 77,
            "Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
            "Date": 24302057,
            "AnswerDate": -2123661683,
            "AnswerEdit": false,
            "CommentEdit": false,
            "ForfeitCount": 0,
            "RewardCount": 0,
            "ThisCountReport": 2,
            "Reported": [{
                "$id": "4",
                "BlockerId": 355,
                "Title": "محتوای غیر اخلاقی",
                "Date": -19527396,
                "ForfeitCount": 0,
                "RewardCount": 0
            }, {
                "$id": "5",
                "BlockerId": 355,
                "Title": "محتوای غیر مرتبط",
                "Date": -19527382,
                "ForfeitCount": 0,
                "RewardCount": 0
            }],
            "Gem": 0
        }, {
            "$id": "6",
            "UserId": 302,
            "UID": "302_UID",
            "Title": "شیدکو",
            "Sender": "شیدکو",
            "Answer": "",
            "Comment": "test 2",
            "ProductTitle": null,
            "CommentId": 77,
            "Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
            "Date": 24302057,
            "AnswerDate": -2123661683,
            "AnswerEdit": false,
            "CommentEdit": false

        }]

    },
    "StatusCode": "Created",
    "Description": null
}

And I do these step, but nothing happens

JObject json1 = JObject.Parse(strMyJson);
    _CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
    _CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
    _CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
    JsonSerializer serializer = new JsonSerializer();
    _CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));

And here is my class and function:

public static T ConvertJsonToClass<T>( string json)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Deserialize<T>(json);
    }

}

public class _CommentAdmindto
{
    public long dateTime { get; set; }

    public IQueryable<CommentDtoAdmin> list { get; set; }
}

public class CommentDtoAdmin
{
    public long UserId { get; set; }
    public string UID { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }

    public string ProductTitle { get; set; }
    public long CommentId { get; set; }

    public string Logo { get; set; }
    public long Date { get; set; }

    public long AnswerDate { get; set; }

    public bool AnswerEdit { get; set; }

    public bool CommentEdit { get; set; }
}
Hille
  • 2,123
  • 22
  • 39
Dav
  • 53
  • 1
  • 1
  • 5

4 Answers4

15

Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :

public class Reported
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public int BlockerId { get; set; }
    public string Title { get; set; }
    public int Date { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
}

public class List
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public int UserId { get; set; }
    public string UID { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }
    public object ProductTitle { get; set; }
    public int CommentId { get; set; }
    public string Logo { get; set; }
    public int Date { get; set; }
    public int AnswerDate { get; set; }
    public bool AnswerEdit { get; set; }
    public bool CommentEdit { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
    public int ThisCountReport { get; set; }
    public List<Reported> Reported { get; set; }
    public int Gem { get; set; }
}

public class Result
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public int dateTime { get; set; }
    public List<List> list { get; set; }
}

public class RootObject
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public Result Result { get; set; }
    public string StatusCode { get; set; }
    public object Description { get; set; }
}

Now you can deserialize as

var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);

BTW: http://json2csharp.com/ can help to guess your model when working with json.

L.B
  • 114,136
  • 19
  • 178
  • 224
  • 1
    If you're using Visual Studio 2015, it has a built in JSON-to-class feature. Just open a new empty class file and Edit > Paste Special > JSON as classes. Works with XML too. Not always perfect but pretty good. The only thing it missed in this case was the attribute decoration on the ID variables. – PMV Oct 02 '16 at 20:39
2

You seem to be trying to deserialize in a lot of different ways but you don't have a full structure to actually match the json. You miss the outer class (representing the full object) and at least Newtonsoft.Json cannot deserialize to an IQueryable so I changed that to IEnumerable.

string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"محتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"محتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";


var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);

with classes looking like this:

public class Wrapper
{
    public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
    public long dateTime { get; set; }

    public IEnumerable<CommentDtoAdmin> list { get; set; }
}

CommentDtoAdmin is looking the same. Though I must say that this only helps you with the deserialization.

Kennet
  • 86
  • 3
  • Thanks, it's really better , but I have now another error, working on new error.An exception of type 'System.ArgumentException' occurred in System.Web.Extensions.dll but was not handled in user code Additional information: Object of type 'System.Collections.Generic.List`1[AdminApp._CommentReported]' cannot be converted to type 'System.Linq.IQueryable`1[AdminApp._CommentReported]'. – Dav Oct 02 '16 at 19:50
2

Firstly, the $id" properties are synthetic properties added by Json.NET to track and preserve multiple references to the same object. For details, see PreserveReferencesHandling setting.

Thus, if you temporarily remove the "$id" properties, you can upload your JSON to http://json2csharp.com/ and get the following data model:

public class Reported
{
    public int BlockerId { get; set; }
    public string Title { get; set; }
    public int Date { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
}

public class CommentDtoAdmin
{
    public int UserId { get; set; }
    public string UID { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }
    public object ProductTitle { get; set; }
    public int CommentId { get; set; }
    public string Logo { get; set; }
    public int Date { get; set; }
    public int AnswerDate { get; set; }
    public bool AnswerEdit { get; set; }
    public bool CommentEdit { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
    public int ThisCountReport { get; set; }
    public List<Reported> Reported { get; set; }
    public int Gem { get; set; }
}

public class Result
{
    public int dateTime { get; set; }
    public List<CommentDtoAdmin> list { get; set; }
}

public class RootObject
{
    public Result Result { get; set; }
    public string StatusCode { get; set; }
    public string Description { get; set; }
}

I then modified the returned model as follows:

  • I used the name CommentDtoAdmin for the list type.
  • I set the type of the Description property to string.

Now your JSON can be deserialized and re-serialized as follows:

var settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);

var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);

Note that Json.NET has no built-in logic for deserializing the interface IQueryable<T> to a concrete type, so I had to leave the property as public List<CommentDtoAdmin> list { get; set; }. You can always generate a queryable from the list using AsQueryable():

var queryable = root.Result.list.AsQueryable();

Sample fiddle.

dbc
  • 104,963
  • 20
  • 228
  • 340
0

I think you json string does not have correct syntax. It looks like a ']' (end of Array) and a final '}' is missing.

That's what the Visual Studio editor told me when making a json file out of your string after removing all the '\'

rachri
  • 525
  • 6
  • 13