2

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; }
}
3
  • I suppose its a duplicate question stackoverflow.com/questions/4718888/… Commented Oct 2, 2016 at 19:20
  • @HussainPatel on your link , they didn't add it to class, have a look at it please Commented Oct 2, 2016 at 19:30
  • your json not matching with your model Commented Oct 2, 2016 at 19:31

4 Answers 4

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

1 Comment

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.List1[AdminApp._CommentReported]' cannot be converted to type 'System.Linq.IQueryable1[AdminApp._CommentReported]'.
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.

Comments

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 '\'

2 Comments

that's not the answer - you should put that in comment if case something wrong with question
I edit it , json works fine now , but I can't get what I asked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.