Why WordPressPCL on asp.net Post.CreateAsync Does not work? - c#

i cant create a post using the version 2.0.1 on asp.net CORE
This is the Code:
var client = new WordPressClient( "http://sitioweb.com/wp-json/" );
client.Auth.UseBasicAuth( "username", "app_password" );
var post = new Post() {
Title = new Title( "ITCmx" ),
Content = new Content( "Content PostCreate" )
};
var createdPost = await client.Posts.CreateAsync( post );
And get this error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'WordPressPCL.Models.Post' because the type requires a JSON object
(e.g. {"name":"value"}) to deserialize correctly. To fix this error
either change the JSON to a JSON object (e.g. {"name":"value"}) or
change the deserialized type to an array or a type that implements a
collection interface (e.g. ICollection, IList) like List that can be
deserialized from a JSON array. JsonArrayAttribute can also be added
to the type to force it to deserialize from a JSON array. Path '',
line 1, position 1.
I try on Postman and works fine
Could you please help me
Thank you

You need to convert your data to json before sending
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(post);
var createdPost = await client.Posts.CreateAsync( json);

Related

Read List<double> from Json via Newtonsoft in C#

I would like to read a JSON string via the Newtonsoft Json library. It works fine for any basic datatype, but it does not work for a List<double> or any List for that matter.
The test application looks like the following:
static void main()
{
string jsonString = #"
{
'name': 'set1',
'Xvv': {
'parameter': 'hByT',
'values': '[1,2,3]'
}
}";
JObject Json = JObject.Parse(jsonString);
var name = Json["name"].ToString();
var data = Json["Xvv"]["values"].Value<List<double> >(); // Raises error
}
The last line throws the following exception:
System.InvalidCastException: Invalid cast from 'System.String' to 'System.Collections.Generic.List
Is there a way to access the data directly as a List<double>?
In the example JSON you've provided, values is a string. A proper JSON array would be
'values': [1,2,3]
Anyway, after changing the string to the array, .Value<List<double>>() would throw an exception, that a JArray cannot be cast to a JToken - unfortunately I do not really know, why it does not work.
However, JToken.ToObject<T> does the trick, it
Creates an instance of the specified .NET type from the JToken
(see the documentation for ToObject)
With the line
var data = Json["Xvv"]["values"].ToObject<List<double>>();
you can cast the array correctly.
If an IEnumerable would be fine for you, too, you could also use
var data = Json["Xvv"]["values"].Values<double>();

Cannot deserialize the current JSON object error from IMGUR API in C#

I am trying to get all the images from an imgur album. It works fine with all of the albums, except when i try to get images from
this album
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[Imgur.API.Models.Impl.Image]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Here is my code, which throws out the exception.
public async Task<List<IImage>> dosomething()
{
IEnumerable<IImage> image = await Task.Run(AccessTheWebAsync);
return image.ToList(); ;
}
async Task<IEnumerable<IImage>> AccessTheWebAsync()
{
var client = new ImgurClient(token);
var endpoint = new AlbumEndpoint(client);
IEnumerable<IImage> images = await endpoint.GetAlbumImagesAsync(albumlink);
return images;
}
The value for albumlink that you're passing is incorrect, it should not have the #0 on the end.
The value for albumlink should just be Dc2k6.
I'm not sure why the #0 is there, I assume it can select a specific image or something but I couldn't get it to work. To prove it's irrelevant, add any other value after the #:
https://imgur.com/a/Dc2k6#SAUSAGES

JsonSerializationSettingsException was unhandled

I'm trying to get tweets at the homepage of twitter. But, JsonSerializationSettingsException is thrown:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TweetSharp.TwitterStatus' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
listBox1.Items.Clear();
var option = new ListTweetsOnHomeTimelineOptions() { Count = 25, IncludeEntities = false };
var tweets = service.ListTweetsOnHomeTimeline(option);
foreach (var i in tweets)
{
string tweet = String.Format("{0} -> {1}", i.User.ScreenName, i.Text);
listBox1.Items.Add(tweet);
}

how to deserialize an anonymus object in c# [duplicate]

Is it possible to return a dynamic object from a json deserialization using json.net? I would like to do something like this:
dynamic jsonResponse = JsonConvert.Deserialize(json);
Console.WriteLine(jsonResponse.message);
Json.NET allows us to do this:
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);
Output:
1000
string
6
Documentation here: LINQ to JSON with Json.NET
See also JObject.Parse and JArray.Parse
As of Json.NET 4.0 Release 1, there is native dynamic support:
[Test]
public void DynamicDeserialization()
{
dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
jsonResponse.Works = true;
Console.WriteLine(jsonResponse.message); // Hi
Console.WriteLine(jsonResponse.Works); // True
Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
Assert.That(jsonResponse, Is.TypeOf<JObject>());
}
And, of course, the best way to get the current version is via NuGet.
Updated (11/12/2014) to address comments:
This works perfectly fine. If you inspect the type in the debugger you will see that the value is, in fact, dynamic. The underlying type is a JObject. If you want to control the type (like specifying ExpandoObject, then do so.
If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.
var converter = new ExpandoObjectConverter();
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);
I know this is old post but JsonConvert actually has a different method so it would be
var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);
Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
Note: At the time I answered this question in 2010, there was no way to deserialize without some sort of type, this allowed you to deserialize without having go define the actual class and allowed an anonymous class to be used to do the deserialization.
You need to have some sort of type to deserialize to. You could do something along the lines of:
var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());
My answer is based on a solution for .NET 4.0's build in JSON serializer. Link to deserialize to anonymous types is here:
http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx
If you use JSON.NET with old version which didn't JObject.
This is another simple way to make a dynamic object from JSON:
https://github.com/chsword/jdynamic
NuGet Install
PM> Install-Package JDynamic
Support using string index to access member like:
dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);
Test Case
And you can use this util as following :
Get the value directly
dynamic json = new JDynamic("1");
//json.Value
2.Get the member in the json object
dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"
dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m
dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1
3.IEnumerable
dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements
dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use json.a[0]/ json.a[2] to get the elements
dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the json[0].b/json[1].c to get the num.
Other
dynamic json = new JDynamic("{a:{a:1} }");
//json.a.a is 1.
Yes it is possible. I have been doing that all the while.
dynamic Obj = JsonConvert.DeserializeObject(<your json string>);
It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:
ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

How to parse Json output from Visistat API using Json.net

I have a Json string from Visistat.com's API that I am trying to parse in C# with Json.Net. The Json string looks like:
[
["date", "uniques"],
["2014-04-15", "613"],
["2014-04-16", "631"],
["2014-04-17", "593"],
["2014-04-18", "466"],
["2014-04-19", "305"],
["2014-04-20", "294"],
["2014-04-21", "795"],
["2014-04-22", "666"],
["2014-04-23", "625"],
["2014-04-24", "571"],
["2014-04-25", "506"],
["2014-04-26", "342"],
["2014-04-27", "351"],
["2014-04-28", "720"],
["2014-04-29", "606"],
["2014-04-30", "588"],
["2014-05-01", "508"],
["2014-05-02", "545"],
["2014-05-03", "345"],
["2014-05-04", "379"],
["2014-05-05", "833"],
["2014-05-06", "635"],
["2014-05-07", "596"],
["2014-05-08", "530"],
["2014-05-09", "539"],
["2014-05-10", "322"],
["2014-05-11", "290"],
["2014-05-12", "734"],
["2014-05-13", "684"],
["2014-05-14", "555"],
["2014-05-15", "511"]
]
I've created an object to deserialize this into:
public class DateUnique
{
public DateTime date { get; set; }
public int uniques { get; set; }
}
I'm then trying to parse the Json string with:
List<DateUnique> dateuniques = JsonConvert.DeserializeObject<List<DateUnique>>(json);
I then get this Exception:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'VisiStatSystem.DateUnique' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '[0]', line 1, position 2.
I don't see any samples in the Json.net documentation that shows how to deserialize a Json string that looks like what is returned by the VisiStat Api. Any help appreciated!
You are getting this error because your JSON is an array of arrays, not an array of objects, while you are trying to parse it as if it were the latter. You will need a little bit of special handling to deserialize it into a List<DateUnique>.
The following code should work:
JArray array = JArray.Parse(json);
List<DateUnique> list = new List<DateUnique>(array.Count - 1);
for (int i = 1; i < array.Count; i++)
{
list.Add(new DateUnique
{
date = DateTime.ParseExact(array[i][0].ToString(),
"yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),
uniques = int.Parse(array[i][1].ToString())
});
}

Categories