How to create a json string where a property contains a dot (period)?

半城伤御伤魂 提交于 2019-12-22 10:53:06

问题


I'm trying to send an HttpRequest that takes a JSON object like this:

{
   "some.setting.withperiods":"myvalue"
}

I've been creating anonymous objects for my other requests, but I can't do that with this one since the name contains a dot.

I know I can create a class and specify the [DataMember(Name="some.setting.withperiods")] attribute, but there must be a more lightweight solution.


回答1:


There is no "easy" way to achieve this because the . in C# is reserved.

However, you could achieve something pretty close by using a dictionary and collection initializer. It's still somewhat isolated, and doesn't require you to create a custom class.

var obj = new Dictionary<string, object>
{
    { "some.setting.withperiods", "myvalue" }
};

var json = JsonConvert.SerializeObject(obj);
//{"some.setting.withperiods":"myvalue"}



回答2:


You can use "JsonProperty" attribute for the same For example

    [JsonProperty(".Name")]
    public string Name { get; set; }



回答3:


On top of this I want to add how to retrieve the data from the json where it has name property starting with special character as in Web API 2.0 token has ".issued".

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var jsonRespons="json response from the web api";
var issue= JObject.Parse(jsonResponse).GetValue(".issued");



回答4:


if you do it from in javascript, you can easily go back and forth, as shown with:

var obj = {
    "some.setting.withdots":"myvalue"
};
var json = JSON.stringify(obj);
console.log(json);
var str = JSON.parse(json);
console.log(str);

have you tried putting it into a serialized string and sending that, then deserializing on the client-side?

you could do something like

var myAnnon = new
{
    WithPeriod = "value"
};
var j = JsonConvert.SerializeObject(myAnnon);
j = j.Replace("WithPeriod", "some.setting.withdots");



回答5:


You can use a JObject (part of Json.Net's LINQ-to-JSON API) to create the JSON in question:

string json = new JObject(new JProperty("some.setting.withperiods", "myvalue")).ToString();

Fiddle: https://dotnetfiddle.net/bhgTta




回答6:


You could try prefixing your member names with a @ to allow use of literals, but the way to do it is using [DataMember] as you have already mentioned in your question.



来源:https://stackoverflow.com/questions/23121025/how-to-create-a-json-string-where-a-property-contains-a-dot-period

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!