3

I've result from MongoDB called by "mongoDBResult"

[{
    "_id": {
        "$oid": "57e8e914c2ef164375bc0957"
    },
    "user": "456"
},
{
    "_id": {
        "$oid": "57e8ea87bd966f3e6de5361b"
    },
    "user": "admin"
}]

And my Class define

public class Id
{
    public string oid { get; set; }
}

public class User
{       
    public Id _id { get; set; }
    public string user { get; set; }
}

But when i use JsonConvert.DeserializeObject like this :

var user = JsonConvert.DeserializeObject<List<User>>(mongoDBResult);

I can get value of user name , and i want to get value of Id.oid but still always null

Anyone can help me how to convert from MongoDB to C# Class with perfect way ?

2 Answers 2

3

Your problem is here:

JOSN:

"$oid": "57e8e914c2ef164375bc0957"

CODE:

public string oid { get; set; }

In JSON you have $oid in code oid

You can try:

[JsonProperty(PropertyName = "$oid")]
public string oid { get; set; }

Or you can change JSON, if you can.

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

2 Comments

@EddyLee I'm glad that I helped. Mark reply as an answer ;-)
@EddyLee if the answer helped you, mark as correct.
0

Try below code.

 Test routes_list = 
      (Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

1 Comment

var user = (List<User>)JsonConvert.DeserializeObject<List<User>>(mongoDBResult); => still get null at Id.oid

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.