Newtonsoft.Json.Linq.JArray.Parse(string)' has some invalid arguments - c#

I am trying to extract data from D2L for the dropbox submissions using API's I have a link which returns a Json Array as per told on the documentation and from this Array I just need the Id feild nothing else.
I have tried to convert this Array into dynamic Object but that didn't help.
Here is my code.
var client = new RestClient("https://" + LMS_URL);
var authenticator = new ValenceAuthenticator(userContext);
string Link = "/d2l/api/le/1.12/UnitID/dropbox/folders/UniID/submissions/";
var request = new RestRequest(string.Format(Link));
request.Method = Method.GET;
authenticator.Authenticate(client, request);
var response = client.Execute(request);
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(response.Content);
Response.Write(jsonString);
//var splashInfo = JsonConvert.DeserializeObject<ObjectD>(response.Content);
dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);
var parsedObject = jsonResponse.Parse(jsonResponse);
string json = jsonResponse;
var popupJson = parsedObject["id"].ToString();
What my goal is that grab the list of ID's from this response and loop through them, these ID's are the key for my next API route.
Here is a glance at what I get from the response:
[
{
"Id": 2021,
"CategoryId": null,
"Name": "Graded Assignment: Part 1",
"CustomInstructions": {
"Text": "Directions:\r\nCOMPLETE the following TestOut Activities\r\n\r\n1.2.10 Practice Questions\r\n1.3.8 Practice Questions\r\n\r\nGo to TestOut to complete the Assignment."
//Other properties omitted
}
//Other properties omitted
}
]

The outermost container in the JSON returned is an array, so you need to deserialize to a collection type as specified in the Newtonsoft's Serialization Guide: IEnumerable, Lists, and Arrays.
Since you only care about the Id property of the object(s) in the array, you can use JsonConvert.DeserializeAnonymousType to deserialize just the interesting value(s):
var ids = JsonConvert.DeserializeAnonymousType(response.Content, new [] { new { Id = default(long) } })
.Select(o => o.Id)
.ToList();
And if you are certain the outermost array will contain exactly one item, you can do:
var id = JsonConvert.DeserializeAnonymousType(response.Content, new [] { new { Id = default(long) } })
.Select(o => o.Id)
.Single();
Alternatively, if you think you will later need to deserialize additional properties, you could make an explicit data model as follows:
public class ObjectId
{
public long Id { get; set; }
}
And do:
var ids = JsonConvert.DeserializeObject<List<ObjectId>>(response.Content)
.Select(o => o.Id)
.ToList();
Notes:
You will need to determine from the API documentation whether long or int is more appropriate for the Id value.
As a general rule I recommend not parsing to dynamic because you lose compile-time checking for correctness. When dealing with completely free-form JSON, parsing to JToken may be a better solution -- but your JSON appears to have a fixed schema, so neither is necessary.
Demo fiddle here.

Related

CosmosDB Update c#: Could not determine JSON object type for type System.String[]

I want to update a field in CosmosDB to array like below:
"Aliases": [
"John",
"Johnny"
],
Below is my code:
dynamic GuideDoc= new
{
id = "00B2845F-F394-5E93-9A26-E70000452562",
type = "Guide",
GuideGuid= "00B2845F-F394-5E93-9A26-E70000452562"
};
ItemResponse<dynamic> clientGuideResponse1 = await this.container.ReadItemAsync<dynamic>(GuideGuid, new PartitionKey(PartitionKey));
dynamic itemBody1 = clientGuideResponse1.Resource;
String[] AliasesConverted= JSONDecoders.DecodeJSONArray(AliasesValues);
itemBody1.Aliases= AliasesConverted;
GuideDoc= itemBody1;
GuideResponse = await this.container.ReplaceItemAsync<dynamic>(GuideDoc, GuideGuid, new PartitionKey(PartitionKey));
The part that stores the data to itemBody1.Aliases is returning an error "Could not determine JSON object type for type System.String[]"
How do I make it save the value to Aliases as an array?
The easiest way to add new properties while keeping everything else intact is deserializing it into a Dictionary. As example:
var response = await container.ReadItemAsync<Dictionary<string, object>>(id, partitionKey);
var item = response.Resource;
item["Aliases"] = new[] { "John", "Johnny" };
await container.ReplaceItemAsync(item, id, partitionKey);
The reason it doesn't work is because the deserializer will return the result as JObject when you use dynamic as type. You can't navigate the JObject through the properties as if it were deserialized into a class with properties. The error you describe is a bit different than I would have thought though.

JsonConvert.DeserializeAnonymousType definition syntax issue

I have the following code:
var definition = new { result = "", accountinformation = new[] { "" , "" , "" } };
var accountInformationResult = JsonConvert.DeserializeAnonymousType(responseBody, definition);
The account information structure comes back from an endpoint as an array with each element being another array containing 3 strings. So the embedded array is not in a key value pair format. With the above definition accountinformation returns null. What should the syntax be for this structure?
For reference this is what is going on in the php endpoint.
$account_information[] = array( $billing_company, $customer_account_number, $customer_account_manager );
This first line is in a loop. Hence the multi-dimensional array.
echo json_encode(array('result'=>$result, 'account_information'=>$account_information));
I know I could use dynamic but why the extra effort?
I assume your json will look something like this:
{
"result": "the result",
"account_information": [
["company1", "account_number1", "account_manager1"],
["company2", "account_number2", "account_manager2"]
]
}
In that case you should be able to deserialize with the following definition (note the underscore in account_information:
var definition = new { result = "", account_information = new List<string[]>() };
In json you are allowed to add extra properties as you please while your data model changes. So if you define a data model that does not include one of these properties, the property will simple be ignored. In your case the definition does not have a property called account_information (exactly), so this part of the json is ignored while deserializing.
EDIT:
If it's going to be an anonymous abject anyway, you may also consider parsing into a JObject:
var obj = JObject.Parse(responseBody);
string firstCompany = obj["account_information"][0][0];
string secondCompany = obj["account_information"][1][0];

Serialize Enum Values and Names to JSON

This question is related, but IMHO not identical to
How do I serialize a C# anonymous type to a JSON string?
Serialize C# Enum Definition to Json
Whilst testing, I've also stumbled across this culprit LinqPad which made my life difficult:
Why does LINQPad dump enum integer values as strings?
Now, my actual question:
My application (in particular SyncFusion component datasources, such as MultiSelect) requires enumerations in JSON format, e.g. something like this:
[ {"Id":0,"Name":"Unknown"},{"Id":1,"Name":"Open"},{"Id":2,"Name":"Closed"},{"Id":3,"Name":"Approve"} ]
UPDATE
As dbc pointed out, my question may not have been clear enough. I do not want to serialize one entry of the enumeration, but the whole struct. The JSON could then be used for a data source in Javascript, e.g. for a , simplified:
<option value=0>Unknown</option>
<option value=1>Open</option> etc
The JSON object is identical to an Enum in a namespace (with the exception that I have given the a property name to the Key and Value of each entry:
public enum ListOptions
{
Unknown = 0,
Open = 1,
Closed = 2,
Approve = 3
}
I've struggled with Enums, all the other approaches such as specifying a Json StringConverter etc did't yield all options in an array, so I ended up using Linq. My View Model now has a string property like this:
public string CrewListOption => JsonConvert.SerializeObject(Enum.GetValues(typeof(ListOptions))
.Cast<int>()
.Select(e => new { Id = (int) e, Name = typeof(ListOptions).GetEnumName(e) }));
Given that I'm pretty much a beginner with ASP.Net Core, I find it hard to believe that this should be a good solution. Yet I find it hard to find straight-forward better examples of the same thing.
I'd appreciate it if you might be able to help me improve this, and make it potentially more generically useful to "export" whole enumerations to JSON.
Here's the full LinqPad (where Newtonsoft.Json is imported from GAC):
void Main()
{
Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = e, Name = (ListOptions) e } ).Dump(); // these are identical, except for the typeof()
Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = (int) e, Name = typeof(ListOptions).GetEnumName(e) }).Dump(); // is typeof(MyEnumType) better?
string JsonString = JsonConvert.SerializeObject(Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = (int) e, Name = typeof(ListOptions).GetEnumName(e) }));
JsonString.Dump(); // [{"Id":0,"Name":"Unknown"},{"Id":1,"Name":"Open"},{"Id":2,"Name":"Closed"},{"Id":3,"Name":"Approve"}]
}
public enum ListOptions {
Unknown = 0,
Open = 1,
Closed = 2,
Approve = 3
};
You may have static method like
public static EnumToDictionary<string, string> EnumToDictionary<T>() where T: Enum
{
var res = Enum.GetValues(typeof(T)).Cast<T>()
.ToDictionary(e => Convert.ToInt32(e).ToString(), e => e.ToString());
return res;
}
then for Serializing as object
var enumValues= EnumToDictionary<ListOptions>();
var result = JsonConvert.SerializeObject(enumValues);
for serializing as array
var enumValues= EnumToDictionary<ListOptions>().ToArray();
var result = JsonConvert.SerializeObject(enumValues);
Here is an example from Microsoft Docs that convert Enum to Dictionary
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#enum-constraints
Then you can serialize the dictionary to JSON.

LINQ need to parse JSON out of a column

In a table, Leads, there is a column Data that contains a JSON string. In a LINQ statement, I need to extract a field from that JSON:
var results = from l in leads
select new MyLeadObject
{
LeadID = l.LeadID,
...
RequestType = (string)l.Data["RequestTypeID"]
};
Here's a shortened version of the JSON:
{
"RequestTypeID":1
}
RequestTypeID is a string.
I've been reading other threads and trying to cobble this together. Not having much luck.
EDIT:
With help from Nkosi, I got this far:
RequestType = (string)JSONNetSerialization.DeserializeJsonNet<LeadData>(l.Data).RequestTypeID
The only problem is that LeadData.RequestTypeID is an enum, so it won't convert the enum to a string. I'm not sure how to get the value of the enum instead of the entire enum itself. Outside of LINQ I could do this: RequestTypeID.GetDisplayName(); but .GetDisplayName() is not recognized by LINQ.
You can use Json.Net to parse the JSON in Data field to get the property.
var results = leads.Select(l =>
new MyLeadObject {
LeadID = l.LeadID,
//...
RequestType = (string)JsonConvert.DeserializeObject(l.Data)["RequestTypeID"]
});

json.net IEnumerable

I have the following json file
{"fields":[
{
"status":"active",
"external_id":"title",
"config":{},
"field_id":11848871,
"label":"Title",
"values":[
{
"value":"Test Deliverable"
}
],
"type":"text"
},{
"status":"active",
"external_id":"client-name",
"config":{},
"field_id":12144855,
"label":"Client Name",
"values":[
{
"value":"Chcuk Norris"
}
],
"type":"text"
}}
And I want to select the value of the field that has its external_id = "title" for example, I'm using Json.Net and already parsed the object. How do i do this using lambda or linq on the Json object, I trird something like this
JObject o = JObject.Parse(json);
Title = o["fields"].Select(q => q["extenral_id"].Values[0] == "title");
Which is not event correct in terms of syntax. I'm not very proficient in Lambda or Linq thought its been there for a while. Appreciate the help
Thanks
Yehia
Or you can do this:
string json = "{\"fields\":[{\"status\":\"active\",\"external_id\":\"title\",\"config\":{},\"field_id\":11848871,\"label\":\"Title\",\"values\":[{\"value\":\"Test Deliverable\"}],\"type\":\"text\"},{\"status\":\"active\",\"external_id\":\"client-name\",\"config\":{},\"field_id\":12144855,\"label\":\"Client Name\",\"values\":[{\"value\":\"Chcuk Norris\"}],\"type\":\"text\"}]}";
JObject obj = JObject.Parse(json);
JArray arr = (JArray)obj["fields"];
var externalIds = arr.Children().Select(m=>m["external_id"].Value<string>());
externalIds is a IEnumerable array of string
Or you can chain it together and select the object in one line:
var myVal = JObject.Parse(json)["fields"].Children()
.Where(w => w["external_id"].ToString() == "title")
.First();
From there you can append whatever selector you want ie if you want the external_id value then append ["external_id"].ToString() to the end of the first() selector.
Build classes for your objects first, then parse them so you can access them correctly and its no anonymous type anymore.
For example this classes:
class MyJson {
public List<MyField> fields {get;set;}
}
class MyField {
public string status {get;set;}
public string external_id {get;set;}
// and so on
}
Then use that class for parsing the json (don't know the exact syntax right now) like this:
var o = Json.Parse(json, typeof(MyJson));
And then you can select your data easily with Linq and have intellisense in VS (or similar dev env):
var myData = o.fields.Where(q=>q.external_id=="title");
If you had your JSON converted to objects (basically what Marc suggested), the LINQ query would look something like:
o.fields.Single(q => q.external_id == "title")
But if you don't want to do that, you have to access the values by string keys. If you don't want to convert the type of the value, you can simply use indexing (["key"]). But if you want to convert the type, you can use Value<Type>("key"). Putting it together, the whole query might be:
o["fields"].Single(q => q.Value<string>("external_id") == "title")

Categories

Resources