deserialize conplex json and access property in xamarin - json

hello everyone i am fetching some json data from server and i want to desalinize that complex json and add in custom object and i dont know how to access that property value .
Here is the json data format
[
{
"Id": 1,
"AlbumId": 2,
"Name": "sample string 3",
"Url": "sample string 4",
"ShareUrl": "sample string 5",
"Selected": true,
"Comment": "sample string 6",
"Album": {
"Id": 1,
"Name": "sample string 2",
"PhotoGrapherId": 3,
"ClientId": 4,
"EventType": "sample string 5",
"EventDate": "2017-10-11T12:06:33.735998+05:30",
"Status": "sample string 7",
"Url": "sample string 8",
"CreatedOn": "2017-10-11T12:06:33.735998+05:30",
"CreatedBy": "sample string 10",
"Client": {
"Id": 1,
"Name": "sample string 2",
"ContactPersonName": "sample string 3",
"ContactPersonMobile": "sample string 4",
"ContactPersonEmail": "sample string 5",
"CreatedOn": "2017-10-11T12:06:33.735998+05:30",
"CreatedBy": "sample string 7",
"Albums": []
},
"PhotoGrapher": {
"Id": 1,
"Name": "sample string 2",
"ContactPersonName": "sample string 3",
"ContactPersonMobile": "sample string 4",
"ContactPersonEmail": "sample string 5",
"CreatedOn": "2017-10-11T12:06:33.735998+05:30",
"CreatedBy": "sample string 7",
"Albums": []
},
"Photos": []
}
},
{
"Id": 1,
"AlbumId": 2,
"Name": "sample string 3",
"Url": "sample string 4",
"ShareUrl": "sample string 5",
"Selected": true,
"Comment": "sample string 6",
"Album": {
"Id": 1,
"Name": "sample string 2",
"PhotoGrapherId": 3,
"ClientId": 4,
"EventType": "sample string 5",
"EventDate": "2017-10-11T12:06:33.735998+05:30",
"Status": "sample string 7",
"Url": "sample string 8",
"CreatedOn": "2017-10-11T12:06:33.735998+05:30",
"CreatedBy": "sample string 10",
"Client": {
"Id": 1,
"Name": "sample string 2",
"ContactPersonName": "sample string 3",
"ContactPersonMobile": "sample string 4",
"ContactPersonEmail": "sample string 5",
"CreatedOn": "2017-10-11T12:06:33.735998+05:30",
"CreatedBy": "sample string 7",
"Albums": []
},
"PhotoGrapher": {
"Id": 1,
"Name": "sample string 2",
"ContactPersonName": "sample string 3",
"ContactPersonMobile": "sample string 4",
"ContactPersonEmail": "sample string 5",
"CreatedOn": "2017-10-11T12:06:33.735998+05:30",
"CreatedBy": "sample string 7",
"Albums": []
},
"Photos": []
}
}
]
I want to deserialize that json data in my cutom object and access each property dynamically.
i tried as follow
PhotoJson myListObj = JsonConvert.DeserializeObject<PhotoJson>(responseText, settings);
and PhotoJson.cs
class PhotoJson
{
public string Id { get; set; }
public string AlbumId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string ShareUrl { get; set; }
public string Selected { get; set; }
public string Comment { get; set; }
}
Please any help me get it sort out my problem.i am not getting ore help on net also.

Actually the Json is usually a List of your class object
Using the following would do the trick
List<PhotoJson> myListObj = JsonConvert.DeserializeObject<PhotoJson>(responseText, settings);
or
var myListObj = JsonConvert.DeserializeObject<PhotoJson>(responseText, settings);
And then Simply using Linq to get the specific data would do the trick.
And i'm pretty sure the model class you have created is not proper you should update it as per the what Json is returning or else things wont work properly

Related

Parse unstructured json in golang

Is there any solution to parse an unstructured json(text) data?
below is a sample response of a web requst that i want to parse and access data (the inner list)
res,err := http.Get("url_of_server")
[[
{
"id": "1",
"text": "sample text",
"user": {
"user_id": "1",
"username": "user1"
},
"created_at_utc": "2022-12-20T16:38:06+00:00",
"status": "Active"
},
{
"id": "2",
"text": "sample text",
"user": {
"user_id": "2",
"username": "user2"
},
"created_at_utc": "2022-12-01T10:15:00+00:00",
"status": "Active"
}
],
"{"code": "hsdvnkvuahudvhafdlfv",
"is_updated": true}",
null
]
what i want to get is:
[
{
"id": "1",
"text": "sample text",
"user": {
"user_id": "1",
"username": "user1"
},
"created_at_utc": "2022-12-20T16:38:06+00:00",
"status": "Active"
},
{
"id": "2",
"text": "sample text",
"user": {
"user_id": "2",
"username": "user2"
},
"created_at_utc": "2022-12-01T10:15:00+00:00",
"status": "Active"
}
]
in python it is possible by easily using res.json()[0]
I have tried using json.Unmarshal() to a map and also struct but does not work,
i don't know how to get rid of this part of response:
"{"code": "hsdvnkvuahudvhafdlfv",
"is_updated": true}",
null
Declare a type for the items:
type Item struct {
ID string `json:"id"`
Text string `json:"text"`
User struct {
UserID string `json:"user_id"`
Username string `json:"username"`
} `json:"user"`
CreatedAtUtc time.Time `json:"created_at_utc"`
Status string `json:"status"`
}
Declare a slice of the items:
var items []Item
Declare a slice representing the entire JSON thing. The first element is the items.
var v = []any{&items}
Unmarshal to v. The items slice will have the values that you are looking for. The second and third elements of v will contain the values you want to ignore.
err := json.Unmarshal(data, &v)
Run the code in the GoLang PlayGround.
Go's standard JSON library is not as flexible as others when it comes to dealing with unexpected or uncontrolled input.
A great alternative is tidwall's gjson.
Example code with gjson:
package main
import (
"fmt"
"github.com/tidwall/gjson"
)
const textInput = `[[
{
"id": "1",
"text": "sample text",
"user": {
"user_id": "1",
"username": "user1"
},
"created_at_utc": "2022-12-20T16:38:06+00:00",
"status": "Active"
},
{
"id": "2",
"text": "sample text",
"user": {
"user_id": "2",
"username": "user2"
},
"created_at_utc": "2022-12-01T10:15:00+00:00",
"status": "Active"
}
],
"{"code": "hsdvnkvuahudvhafdlfv",
"is_updated": true}",
null
]`
func main() {
jsonBody := gjson.Parse(textInput)
fmt.Println(jsonBody.Get("0"))
}

Getting Newtonsoft.Json.JsonSerializationException error when deserializing a Json object

I'm having an issue when trying to send Docusign envelope with custom recipient mail (using recipientMailNotification) trough its API service. My controller receives the request properly, but before it sends to docusign service it deserializes into an object, and that's when the error occurs.
**JSON Request:**
"Recipients": [{
"Order": 1,
"Name": "Andre Test ",
"Email": "andre#test.com",
"SignerType": "SIGNER",
"DocusignSignerType": 0,
"SignatureType": "ELECTRONIC",
"EtapaFinalizada": false,
"EmailNotification":{
"emailBody": "SIGN AS SIGNER",
"emailSubject": "SIGNER SIGNATURE REQUIRED"
}
},
{
"Order": 2,
"Name": "Luis Teste",
"Email": "luis#test.com",
"SignerType": "WITNESS",
"DocusignSignerType": 0,
"SignatureType": "ELECTRONIC",
"EtapaFinalizada": false,
"EmailNotification": {
"emailBody": "SIGN AS WITNESS",
"emailSubject": "WITNESS SIGNATURE REQUIRED"
}
}
]
Gives me the error:
'Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[eSignature.
Providers.Docusign.Entities.RecipientEmailNotification]'
I'm not using a list<> or array of any type. is just a standard property nested inside another.
Tried the solution listed here but still getting the error.
Using Json2CSharp gives me same structure as my current class so I assume it is correct Json.
EDIT: Please note that I'm not even expeting an array or List on my class property:
public class Destinatario
{
public int Order { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string SignerType{ get; set; }
public int DocusignSignerType{ get; set; }
public string SignatureType{ get; set; }
public bool EtapaFinalizada { get; set; }
public RecipientEmailNotification EmailNotification { get; set; }
}
Recipients JSON looks like this:
"recipients": {
"signers": [{
"email": "test1#email.com",
"name": "Name 1",
"recipientId": "1",
"routingOrder": "1",
"tabs": {
"signHereTabs": *[{
"xPosition": "100",
"yPosition": "100",
"documentId": "1",
"pageNumber": "1"
}]
}
},
{
"email": "test2#email.com",
"name": "Name 2",
"recipientId": "2",
"routingOrder": "2",
"tabs": {
"initialHereTabs": *[{
"xPosition": "100",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1"
}],
"signHereTabs": [*{
"xPosition": "200",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1"
}]
}
}
],
"carbonCopies": [{
"email": "test3#email.com",
"name": "Name 3",
"recipientId": "3",
"routingOrder": "3"
},
{
"email": "test*4#email.com",
"name": "Name 4",
"recipientId": "4",
"routingOrder": "3"
}
]
}
You do not have it separated into different kinds of recipients so your JSON is invalid.
Please see https://developers.docusign.com/esign-rest-api/guides/features/recipients for more information.

Swift Codable, array value as key

So this is my JSON:
{
"items": [{
"name": "Item 1",
"description": "This is Item 1",
"categories": ["Category1", "Category2", "Category3", "Category4"],
"size": ["M", "L"]
},{
"name": "Item 2",
"description": "This is Item 2",
"categories": ["Category1", "Category3", "Category4"],
"size": ["M"]
}]
}
I can read and print it perfectly fine
However, I want to change this structure to this one where each item is separated by category and size, and where the categories are used as keys.
{
"categories": {
"category1": [{
"name": "Item 1",
"description": "This is Item 1",
"size": "M"
},{
"name": "Item 1",
"description": "This is Item 1",
"size": "L"
},{
"name": "Item 2",
"description": "This is Item 2",
"size": "M"
}...],
"category2": [{
...
}]
}
I've created the following data structure but I'm not quite sure how to continue:
struct Categories: Codable {
let category: String
let items: [Item]
struct Item: Codable {
let name, description, size: String
}
}
Is Codable the right solution for this? If so; how would I go on to achieve this?
For your current json you need
struct Root: Codable {
let categories: [String:[Item]]
}
struct Item: Codable {
let name, description, size: String
}
But I think it's better to make it like this
{
"category1": [{
"name": "Item 1",
"description": "This is Item 1",
"size": "M"
},{
"name": "Item 1",
"description": "This is Item 1",
"size": "L"
},{
"name": "Item 2",
"description": "This is Item 2",
"size": "M"
}],
"category2": [{
}]
}
Which will make you do this
let res = try? JSONDecoder().decode([String:[Item]].self,from:jsonData)
Without the Root struct and the useless categories key

How can i parse JSON from Webservice result with Gson

When i send request to server.
I get result data with this format:
{
"menu": {
"7": [{
"m_id": "1",
"m_flag": "1",
"m_type": "7",
"m_name": "\u30cf\u30a4\u30cd\u30b1\u30f3",
"m_price": "1000",
"m_cost": "158",
"m_regist_date": "0000-00-00",
"p_id": "0"
}, {
"m_id": "2",
"m_flag": "1",
"m_type": "7",
"m_name": "\u30ae\u30cd\u30b9",
"m_price": "1000",
"m_cost": "250",
"m_regist_date": "0000-00-00",
"p_id": "0"
},....
"2": [{
"m_id": "149",
"m_flag": "1",
"m_type": "2",
"m_name": "\u30da\u30fc\u30bf\u30fc\u30e4\u30b3\u30d6\u30ea\u30fc\u30b9\u30ea\u30f3\u30b0",
"m_price": "6500",
"m_cost": "2100",
"m_regist_date": "0000-00-00",
"p_id": "0"
}, {
"m_id": "150",
"m_flag": "1",
"m_type": "2",
"m_name": "\u30a4\u30d3\u30b9\u30af\u30b9 \u30eb\u30fc\u30b8\u30e5 08",
"m_price": "6800",
"m_cost": "2520",
"m_regist_date": "0000-00-00",
"p_id": "0"
},...
}
It very long . So when i used :
JSONObject json = jsonParser.makeHttpRequest(REQUEST_URL, "POST",params);
menu = json.getJSONArray("menu");
I get error and can't get data of JSON:
Error parsing data org.json.JSONException: End of input at character 0 of
How can i Parse data of json , I do not know how to use Gson.
AND how can i get data of KEY "2".
Thank you very much!
If you are looking for GSON parsing then find it here.
Simply create a POJO class and map it to JSON string.
Sample code:
class MenuDetail {
private String m_id;
private String m_flag;
private String m_type;
private String m_name;
private String m_price;
private String m_cost;
private String m_regist_date;
private String p_id;
// getter & setter
}
...
Type type = new TypeToken<Map<String, Map<String, ArrayList<MenuDetail>>>>() {}.getType();
Map<String, Map<String, ArrayList<MenuDetail>>> data = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
output:
{
"menu": {
"7": [
{
"m_id": "1",
"m_flag": "1",
"m_type": "7",
"m_name": "name",
"m_price": "1000",
"m_cost": "158",
"m_regist_date": "0000-00-00",
"p_id": "0"
},
{
"m_id": "2",
"m_flag": "1",
"m_type": "7",
"m_name": "name",
"m_price": "1000",
"m_cost": "250",
"m_regist_date": "0000-00-00",
"p_id": "0"
}
]
}
}

List<Object> serialization not working with multiple objects

I have the following classes
[DataContract]
public class Video
{
[Key]
[DataMember(IsRequired = false)]
public int VideoId { get; set; }
[DataMember(IsRequired = false)]
public int UserId { get; set; }
[Required]
[DataMember ]
public string Title { get; set; }
[Required]
[DataMember]
public virtual IList<Tag> Tags { get; set; }
}
[DataContract]
public class Tag
{
[Key]
[Required]
[DataMember(IsRequired = false)]
public int? TagId { get; set; }
[DataMember(IsRequired = true)]
[Required]
public string Name { get; set; }
[IgnoreDataMember]
public virtual IList<Video> Videos { get; set; }
}
In my WebAPI controller, I call this:
var videos = _service.GetVideos();
return Request.CreateResponse(HttpStatusCode.OK, videos);
Which calls this:
public IList<Video> GetVideos()
{
using (var db = CreateContext())
{
return db.Videos.Include("Tags").ToList();
}
}
Yet over the wire, this is what I get:
[{
"$id": "8",
"tags": [
{
// CORRECT SERIALIZATION
"$id": "9",
"tagId": 1,
"name": "Example",
"count": 5
}
],
"videoId": 18,
"userId": 3,
"title": "Test Video",
"thumbnail": "http://i.imgur.com/gV3J2Uf.png",
"source": "test source"
},
{
"$id": "19",
"tags": [
{
// WTF?
"$ref": "9"
}
],
"videoId": 28,
"userId": 6,
"title": "Test Video",
"thumbnail": "http://i.imgur.com/gV3J2Uf.png",
"source": "test source"
},
{
"$id": "20",
"tags": [
{
// CORRECT AGAIN
"$id": "21",
"tagId": 10,
"name": "funny",
"count": 2
}
],
"videoId": 29,
"userId": 6,
"title": "TEST VID",
"thumbnail": "https://i.imgur.com/SWOQSOf.jpg",
"source": "test source"
},
{
"$id": "22",
"tags": [
{
// INCORRECT
"$ref": "9"
},
{
"$ref": "21"
}
],
"videoId": 30,
"userId": 6,
"title": "TEST VID",
"thumbnail": "https://i.imgur.com/R7lVobX.jpg",
"source": "test source"
}
For some reason - tags is sometimes serializing correctly, and sometimes not. Any idea what I'm doing wrong?
You have circular references in your object graph. They cannot be JSON serialized properly, the serializer detects this condition and automatically makes references ($ref). when you are loading the object graph using EF there are circular references between those objects in memory which cannot be represented correctly in JSON.
I would recommend you breaking the circular references graph by using a view model and then sending the view model over the wire instead of directly returning your autogenerated EF models.