Hello I have one json text one attribute includes $type. I want to change it to type in my response but it is again written as $type.
public class DocumentDTO
{
public string Version { get; set; }
public List<DocumentInfo> Documents { get; set; }
}
public class DocumentInfo
{
public string DocumentState { get; set; }
public DocumentData DocumentData { get; set; }
public string DocumentAsBase64 { get; set; }
}
public class DocumentData
{
public string Name { get; set; }
[JsonProperty(PropertyName = "$type")]
public string type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonProperty(PropertyName = "$type")]
public string type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
I am deserializing like below code
DocumentDTO documentResult = JsonConvert.DeserializeObject<DocumentDTO>(jsonText);
In my api response it is still as $type even I want type. What is my missing here?
Below one is not my want
{
"message": null,
"hasError": false,
"errors": [],
"data": [
{
"version": "1.1",
"documents": [
{
"documentState": "Correct",
"documentData": {
"name": "OthersTWN",
"$type": "Document",
"fields": [
{
"name": "DocumentGUID",
"$type": "Text",
"suspiciousSymbols": null,
"recognizedValue": null,
"value": ""
}
]
},
"documentAsBase64": ""
}
]
}
],
"percentage": 100
}
Below one is my want
{
"message": null,
"hasError": false,
"errors": [],
"data": [
{
"version": "1.1",
"documents": [
{
"documentState": "Correct",
"documentData": {
"name": "OthersTWN",
"type": "Document",
"fields": [
{
"name": "DocumentGUID",
"type": "Text",
"suspiciousSymbols": null,
"recognizedValue": null,
"value": ""
}
]
},
"documentAsBase64": ""
}
]
}
],
"percentage": 100
}
Thanks in advance
Related
The problem I am facing is that I am getting 0's for the values I ask for in the JSON.
I recently asked a question here about getting specific values from a JSON array response that come from an API.
Now I have a new JSON response from a different route and in there I want one values and its called EntityId its places in a block of Entity See the code for more details, I would like to grab that from this response and place them in a list or Array because it tells me who submitted the assignment in D2L.
UPDATE- After getting comments from a user I used JSON to C# tool to create the full class with all the values but I still get the values as 0,0,0,0.
Right now I am getting 0,0,0,0 values and not getting the actual values if it's possible I would like to grab the whole block on Entity.
JSON
[
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 27,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-01T15:25:04.130Z",
"Comment": {
"Text": "",
"Html": ""
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 1245,
"FileName": "1.2.10.png",
"Size": 144407
},
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 292,
"FileName": "1.3.8.png",
"Size": 127869
}
]
}
],
"CompletionDate": "2019-08-01T15:25:04.130Z"
},
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 41,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-03T03:31:43.807Z",
"Comment": {
"Text": " \nAlex",
"Html": "<p></p>\n<p>Alex</p>"
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 313,
"FileName": "Capture 1.2.10 Questions.PNG",
"Size": 97722
}
]
}
],
"CompletionDate": "2019-08-03T03:31:43.807Z"
}
]
Classes:
public class Entity
{
public string DisplayName { get; set; }
public int EntityId { get; set; }
public string EntityType { get; set; }
public bool Active { get; set; }
}
public class SubmittedBy
{
public string Identifier { get; set; }
public string DisplayName { get; set; }
}
public class Comment
{
public string Text { get; set; }
public string Html { get; set; }
}
public class File
{
public bool IsRead { get; set; }
public bool IsFlagged { get; set; }
public bool IsDeleted { get; set; }
public int FileId { get; set; }
public string FileName { get; set; }
public int Size { get; set; }
}
public class Submission
{
public int Id { get; set; }
public SubmittedBy SubmittedBy { get; set; }
public DateTime SubmissionDate { get; set; }
public Comment Comment { get; set; }
public IList<File> Files { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
public int Status { get; set; }
public object Feedback { get; set; }
public IList<Submission> Submissions { get; set; }
public DateTime CompletionDate { get; set; }
}
Code:
var request = new RestRequest(string.Format(Link));
request.Method = Method.GET;
authenticator.Authenticate(client, request);
var response = client.Execute(request);
var thisasa = JsonConvert.DeserializeObject<List<Example>>
(response.Content).Select(
o => o.Identifier).ToList();
The Example data model shown in your question already can be used to successfully deserialize the JSON shown. All that's left is to pick out the Entity.EntityId property via a Select:
var thisasa = JsonConvert.DeserializeObject<List<Example>>(response.Content)
.Select(o => o.Entity.EntityId)
.ToList();
Demo fiddle #1 here.
Incidentally, if you only need Entity.EntityId you could simplify your data model as follows:
public class Entity
{
public int EntityId { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
}
Demo fiddle #2 here.
(As an aside, since your Example class corresponds to the documented object Dropbox.EntityDropbox, you might want to rename your type to EntityDropbox for clarity.)
I'm working with SwiftType Elastic Search + C# and running into an issue deserializing the response due to the fact that SwiftType returns all of the fields as objects with a raw property (https://swiftype.com/documentation/app-search/api/search) for example:
{
"meta": {
"warnings": [],
"page": {
"current": 1,
"total_pages": 1,
"total_results": 2,
"size": 10
},
"request_id": "6887a53f701a59574a0f3a7012e01aa8"
},
"results": [
{
"phone": {
"raw": 3148304280.0
},
"accounts_balance_ach": {
"raw": 27068128.71
},
"accounts_balance_pending": {
"raw": "46809195.64"
},
"email": {
"raw": "Brisa34#hotmail.com"
},
"accounts_count": {
"raw": 6.0
},
"id": {
"raw": "c98808a2-d7d6-4444-834d-2fe4f6858f6b"
},
"display_name": {
"raw": "The Johnstons"
},
"type": {
"raw": "Couple"
},
"advisor_email": {
"raw": "Cornelius_Schiller14#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T10:42:07+00:00"
},
"source": {
"raw": "event"
},
"accounts_balance": {
"raw": 43629003.47
},
"accounts_donations": {
"raw": 38012278.75
},
"advisor_name": {
"raw": "Cloyd Jakubowski"
},
"_meta": {
"score": 0.42934617
}
},
{
"phone": {
"raw": 2272918612.0
},
"accounts_balance_ach": {
"raw": 35721452.35
},
"accounts_balance_pending": {
"raw": "35117465.2"
},
"email": {
"raw": "Ruby87#yahoo.com"
},
"accounts_count": {
"raw": 1.0
},
"id": {
"raw": "687af11f-0f73-4112-879c-1108303cb07a"
},
"display_name": {
"raw": "Kennith Johnston"
},
"type": {
"raw": "Individual"
},
"advisor_email": {
"raw": "Evangeline_Wisoky92#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T16:16:02+00:00"
},
"source": {
"raw": "website"
},
"accounts_balance": {
"raw": 23063874.19
},
"accounts_donations": {
"raw": 33025175.79
},
"advisor_name": {
"raw": "Ernie Mertz"
},
"_meta": {
"score": 0.39096162
}
}
]
}
I need to map each key to its value, eg results[0].email = "Brisa34#hotmail.com";
I saw a promising option with custom converters but I want to make sure there is not a more dynamic way to do this before I take the verbose approach.
I would suggest using the JsonPathConverter class found in Can I specify a path in an attribute to map a property in my class to a child property in my JSON?. This will allow you to declare a strongly-typed Result class and then easily map each of the properties to the value of the respective raw child value in the JSON without having to declare a ton of awkward single-property classes.
Declare your model as shown below. Note that the Result class needs a [JsonConverter] attribute on it to tie it to the JsonPathConverter (otherwise the property paths will not work and you will get default values in your properties).
public class RootObject
{
public List<Result> results { get; set; }
}
[JsonConverter(typeof(JsonPathConverter))]
public class Result
{
[JsonProperty("phone.raw")]
public string Phone { get; set; }
[JsonProperty("accounts_balance_ach.raw")]
public decimal AccountsBalanceAch { get; set; }
[JsonProperty("accounts_balance_pending.raw")]
public decimal AccountsBalancePending { get; set; }
[JsonProperty("email.raw")]
public string Email { get; set; }
[JsonProperty("accounts_count.raw")]
public decimal AccountsCount { get; set; }
[JsonProperty("id.raw")]
public string Id { get; set; }
[JsonProperty("display_name.raw")]
public string DisplayName { get; set; }
[JsonProperty("type.raw")]
public string Type { get; set; }
[JsonProperty("advisor_email.raw")]
public string AdvisorEmail { get; set; }
[JsonProperty("created_at.raw")]
public string CreatedAt { get; set; }
[JsonProperty("source.raw")]
public string Source { get; set; }
[JsonProperty("accounts_balance.raw")]
public decimal AccountsBalance { get; set; }
[JsonProperty("accounts_donations.raw")]
public decimal AccountsDonations { get; set; }
[JsonProperty("advisor_name.raw")]
public string AdvisorName { get; set; }
[JsonProperty("_meta.score")]
public decimal MetaScore { get; set; }
}
Then you can just deserialize as usual:
var root = JsonConvert.DeserializeObject<RootObject>(json);
Here is a working demo: https://dotnetfiddle.net/wYxwIF
The Most dynamic way for you would be to use The Newtonsoft JObejct class.
It will parse your JSON string into a JSON object for you to use, this is if you do not have a corresponding model and you need to create a dynamic JSON object.
For example:
string json = "{
"meta": {
"warnings": [],
"page": {
"current": 1,
"total_pages": 1,
"total_results": 2,
"size": 10
},
"request_id": "6887a53f701a59574a0f3a7012e01aa8"
},
"results": [
{
"phone": {
"raw": 3148304280.0
},
"accounts_balance_ach": {
"raw": 27068128.71
},
"accounts_balance_pending": {
"raw": "46809195.64"
},
"email": {
"raw": "Brisa34#hotmail.com"
},
"accounts_count": {
"raw": 6.0
},
"id": {
"raw": "c98808a2-d7d6-4444-834d-2fe4f6858f6b"
},
"display_name": {
"raw": "The Johnstons"
},
"type": {
"raw": "Couple"
},
"advisor_email": {
"raw": "Cornelius_Schiller14#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T10:42:07+00:00"
},
"source": {
"raw": "event"
},
"accounts_balance": {
"raw": 43629003.47
},
"accounts_donations": {
"raw": 38012278.75
},
"advisor_name": {
"raw": "Cloyd Jakubowski"
},
"_meta": {
"score": 0.42934617
}
},
{
"phone": {
"raw": 2272918612.0
},
"accounts_balance_ach": {
"raw": 35721452.35
},
"accounts_balance_pending": {
"raw": "35117465.2"
},
"email": {
"raw": "Ruby87#yahoo.com"
},
"accounts_count": {
"raw": 1.0
},
"id": {
"raw": "687af11f-0f73-4112-879c-1108303cb07a"
},
"display_name": {
"raw": "Kennith Johnston"
},
"type": {
"raw": "Individual"
},
"advisor_email": {
"raw": "Evangeline_Wisoky92#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T16:16:02+00:00"
},
"source": {
"raw": "website"
},
"accounts_balance": {
"raw": 23063874.19
},
"accounts_donations": {
"raw": 33025175.79
},
"advisor_name": {
"raw": "Ernie Mertz"
},
"_meta": {
"score": 0.39096162
}
}
]
}"
JObject result = JObject.Parse(json);
result is now a JSON object and you can access it's properties.
You can use the following link to convert json to C# class. Then can use Newtonsoft Json to parse:
var jsonMessage = "{ \"meta\": { \"warnings\": [], \"page\": { \"current\": 1, \"total_pages\": 1, \"total_results\": 2, \"size\": 10 }, \"request_id\": \"6887a53f701a59574a0f3a7012e01aa8\" }, \"results\": [{ \"phone\": { \"raw\": 3148304280.0 }, \"accounts_balance_ach\": { \"raw\": 27068128.71 }, \"accounts_balance_pending\": { \"raw\": \"46809195.64\" }, \"email\": { \"raw\": \"Brisa34#hotmail.com\" }, \"accounts_count\": { \"raw\": 6.0 }, \"id\": { \"raw\": \"c98808a2-d7d6-4444-834d-2fe4f6858f6b\" }, \"display_name\": { \"raw\": \"The Johnstons\" }, \"type\": { \"raw\": \"Couple\" }, \"advisor_email\": { \"raw\": \"Cornelius_Schiller14#hotmail.com\" }, \"created_at\": { \"raw\": \"2018-10-02T10:42:07+00:00\" }, \"source\": { \"raw\": \"event\" }, \"accounts_balance\": { \"raw\": 43629003.47 }, \"accounts_donations\": { \"raw\": 38012278.75 }, \"advisor_name\": { \"raw\": \"Cloyd Jakubowski\" }, \"_meta\": { \"score\": 0.42934617 } }, { \"phone\": { \"raw\": 2272918612.0 }, \"accounts_balance_ach\": { \"raw\": 35721452.35 }, \"accounts_balance_pending\": { \"raw\": \"35117465.2\" }, \"email\": { \"raw\": \"Ruby87#yahoo.com\" }, \"accounts_count\": { \"raw\": 1.0 }, \"id\": { \"raw\": \"687af11f-0f73-4112-879c-1108303cb07a\" }, \"display_name\": { \"raw\": \"Kennith Johnston\" }, \"type\": { \"raw\": \"Individual\" }, \"advisor_email\": { \"raw\": \"Evangeline_Wisoky92#hotmail.com\" }, \"created_at\": { \"raw\": \"2018-10-02T16:16:02+00:00\" }, \"source\": { \"raw\": \"website\" }, \"accounts_balance\": { \"raw\": 23063874.19 }, \"accounts_donations\": { \"raw\": 33025175.79 }, \"advisor_name\": { \"raw\": \"Ernie Mertz\" }, \"_meta\": { \"score\": 0.39096162 } } ]}";
var message = JsonConvert.DeserializeObject<RootObject>(jsonMessage);
Console.WriteLine(message.meta.page.current); // prints 1
public class Page
{
public int current { get; set; }
public int total_pages { get; set; }
public int total_results { get; set; }
public int size { get; set; }
}
public class Meta
{
public List<object> warnings { get; set; }
public Page page { get; set; }
public string request_id { get; set; }
}
public class Phone
{
public double raw { get; set; }
}
public class AccountsBalanceAch
{
public double raw { get; set; }
}
public class AccountsBalancePending
{
public string raw { get; set; }
}
public class Email
{
public string raw { get; set; }
}
public class AccountsCount
{
public double raw { get; set; }
}
public class Id
{
public string raw { get; set; }
}
public class DisplayName
{
public string raw { get; set; }
}
public class Type
{
public string raw { get; set; }
}
public class AdvisorEmail
{
public string raw { get; set; }
}
public class CreatedAt
{
public DateTime raw { get; set; }
}
public class Source
{
public string raw { get; set; }
}
public class AccountsBalance
{
public double raw { get; set; }
}
public class AccountsDonations
{
public double raw { get; set; }
}
public class AdvisorName
{
public string raw { get; set; }
}
public class Meta2
{
public double score { get; set; }
}
public class Result
{
public Phone phone { get; set; }
public AccountsBalanceAch accounts_balance_ach { get; set; }
public AccountsBalancePending accounts_balance_pending { get; set; }
public Email email { get; set; }
public AccountsCount accounts_count { get; set; }
public Id id { get; set; }
public DisplayName display_name { get; set; }
public Type type { get; set; }
public AdvisorEmail advisor_email { get; set; }
public CreatedAt created_at { get; set; }
public Source source { get; set; }
public AccountsBalance accounts_balance { get; set; }
public AccountsDonations accounts_donations { get; set; }
public AdvisorName advisor_name { get; set; }
public Meta2 _meta { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public List<Result> results { get; set; }
}
I have to:
DeserializeObject - do some changes - SerializeObject
When my Json have miltiple types e.g.
{
"type": "test",
"currentStatus": "Active",
"id": "987",
"items": [
{
"type": "test1",
"id": "123",
"name": "Segment Members",
"memberCount": "0",
"outputTerminals": [
{
"type": "test2",
"id": "123",
"connectedId": "123",
"terminalType": "out"
}
],
"position": {
"type": "Position",
"x": "46",
"y": "14"
},
"isFinished": "true",
"isRecurring": "false",
"segmentId": "123"
},
{
"type": "test5",
"id": "1390",
"name": "Yay! Clickers",
"memberCount": "2",
"position": {
"type": "Position",
"x": "330",
"y": "375"
},
"waitFor": "2592000"
},
{
"type": "test3",
"id": "1391",
"name": "test",
"memberCount": "73",
"outputTerminals": [
{
"type": "test4",
"id": "123",
"connectedId": "123",
"connectedType": "CampaignWaitAction",
"terminalType": "yes"
},
{
"type": "test4",
"id": "123",
"connectedId": "123",
"connectedType": "CampaignWaitAction",
"terminalType": "no"
}
],
"position": {
"type": "Position",
"x": "123",
"y": "123"
},
"testId": "123"
}
]
}
What data type i should use for this operation? dynamic, object, Jobject...? or maybe something else?
I would just create an object and deseriablize it to that type. A lot easier than doing it dynamically. (assuming it will stay in that structure always)
WHAT TO DO
Copy your Json:
`Edit` -> `Paste Special` -> `Paste JSON As CLASSES`
And there you go! You have the Type you want to deserialize to.
var deserializedJson = JsonConvert.DeserializeObject<YourNewObject>(jsonString);
Note: if the pasting of the json class doesn't work, make sure your json is valid: ClickHereToValidateJson
using Newtonsoft.Json;
dynamic collection = new
{
MultipleType = //call function which returns json here
};
//serialize
var jsonSerializedFeed = JsonConvert.SerializeObject(MultipleType);
//deserialize
var jsonSerializedFeed = JsonConvert.DeserializeObject(MultipleType);
Hope it helps
You can create classes and serialize/deserialize json:
public class OutputTerminal
{
public string type { get; set; }
public string id { get; set; }
public string connectedId { get; set; }
public string terminalType { get; set; }
public string connectedType { get; set; }
}
public class Position
{
public string type { get; set; }
public string x { get; set; }
public string y { get; set; }
}
public class Item
{
public string type { get; set; }
public string id { get; set; }
public string name { get; set; }
public string memberCount { get; set; }
public IList<OutputTerminal> outputTerminals { get; set; }
public Position position { get; set; }
public string isFinished { get; set; }
public string isRecurring { get; set; }
public string segmentId { get; set; }
public string waitFor { get; set; }
public string testId { get; set; }
}
public class Root
{
public string type { get; set; }
public string currentStatus { get; set; }
public string id { get; set; }
public IList<Item> items { get; set; }
}
And then:
string json = JsonConvert.SerializeObject(rootObject);
Root root = JsonConvert.DeserializeObject<Root>(json);
Also, you can use dynamic type without classes:
string json = JsonConvert.SerializeObject(dynamicObject);
dynamic obj = JsonConvert.DeserializeObject(json);
How to json accept single value as array?
This json throw exception:
{
"code": "1",
"message": "OK",
"response": {
"partners":
{
"id": "33",
"name": "",
"clienttypeid": "29",
"logo": "",
"description": "",
"website": "www.site.com"
}
}
}
This json parsed correct:
{
"code": "1",
"message": "OK",
"response": {
"partners": [
{
"id": "33",
"name": "",
"clienttypeid": "29",
"logo": "",
"description": "",
"website": "www.site.com"
},
{
"id": "34",
"name": "",
"clienttypeid": "29",
"logo": "",
"description": "",
"website": "www.site.com"
}
]
} }
Model:
public class Partner
{
public string id { get; set; }
public string name { get; set; }
public string clienttypeid { get; set; }
public string logo { get; set; }
public string description { get; set; }
public string website { get; set; }
}
public class Response
{
public List<Partner> partners { get; set; }
}
public class RootObject
{
public string code { get; set; }
public string message { get; set; }
public Response response { get; set; }
}
If you're trying to deserialize to a List, use array notation, even with one element
{
"code":"1",
"message":"OK",
"response":{
"partners":[
{
"id":"33",
"name":"",
"clienttypeid":"29",
"logo":"",
"description":"",
"website":"www.site.com"
}
]
}
}
I used Json.net to convert the partners to array if it is a single object
string Normalize(string json)
{
var jobj = JObject.Parse(json);
if (!(jobj["response"]["partners"] is JArray))
{
jobj["response"]["partners"] = new JArray(jobj["response"]["partners"]);
}
return jobj.ToString();
}
here is my json response that I am trying to deserialize
[{
"Musician": {
"id": "554343",
"Name": "16408",
"Age": "22"
},
"Albums": [{
"id": "34343",
"AlbumName": "Super charge",
"ReleaseDate": "",
"Hits": ""
}, {
"id": "34222",
"AlbumName": "Super 2",
"ReleaseDate": "",
"Hits": ""
}]
},
{
"Musician": {
"id": "554344",
"Name": "16468",
"Age": "32"
},
"Albums": [{
"id": "34323",
"AlbumName": "Awesome one",
"ReleaseDate": "",
"Hits": ""
}, {
"id": "34222",
"AlbumName": "Awesome two",
"ReleaseDate": "",
"Hits": ""
}]
}]
here are my class
public class Musician
{
public string id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
public class Album
{
public string id { get; set; }
public string AlbumName { get; set; }
public string ReleaseDate { get; set; }
public string Hits { get; set; }
}
public class RootObject
{
public Musician Musician { get; set; }
public List<Album> Albums { get; set; }
}
this is the code i am using to deserialize objects
var musicians = JsonConvert.DeserializeObject<List<Musician>>(data);
var album = JsonConvert.DeserializeObject<List<Album>>(data);
musicians variable shows 2 counts of record while debugging but value of elements id,Name,Age always shows null. Not able to recognize what exactly causing it.
You should be deserializing as collection of RootObjects.
var musicians = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(data);
Output