2013-02-26 69 views
13

我如何轉換的通用JObject到駝峯純JSON字符串? 我試着JsonSerializerSettings但不工作(Newtonsoft.Json 4.5.11)JObject與駝峯轉換與JSON.Net

[Test] 
public void should_convert_to_camel_case() 
{ 
    var serializer = JsonSerializer.Create(new JsonSerializerSettings() 
    { 
     ContractResolver = new CamelCasePropertyNamesContractResolver() 
    }); 

    var jo = new JObject(); 
    jo["CamelCase"] = 1; 

    var stringWriter = new StringWriter(); 
    var writer = new JsonTextWriter(stringWriter); 
    serializer.Serialize(writer,jo); 

    var serialized = stringWriter.ToString(); 

    Assert.AreEqual("{\"camelCase\":1}", serialized); 
} 

UPDATE 根據http://json.codeplex.com/workitem/23853不能做(TNX到@nick_w的鏈接)

回答

6

this,序列化JObject這樣,當合同解析器被忽略。通過頁面上的解決方法的啓發,你可以做這樣的事情:

var jo = new JObject(); 
jo["CamelCase"] = 1; 

string json = JsonConvert.SerializeObject(jo); 
var jObject = JsonConvert.DeserializeObject<ExpandoObject>(json); 

var settings = new JsonSerializerSettings() 
{ 
    ContractResolver = new CamelCasePropertyNamesContractResolver() 
}; 

var serialized = JsonConvert.SerializeObject(jObject, settings); 

Assert.AreEqual("{\"camelCase\":1}", serialized); 

編輯:

有關Dictionary<string, object>好一點。所以,做這種方式跳過的附加JsonConvert.SerializeObject,但它也減輕了需要對ExpandoObject,如果你使用的是.NET 3.5這是非常重要的。

Dictionary<string, object> jo = new Dictionary<string, object>(); 
jo.Add("CamelCase", 1); 

var settings = new JsonSerializerSettings() 
{ 
    ContractResolver = new CamelCasePropertyNamesContractResolver() 
}; 

var serialized = JsonConvert.SerializeObject(jo, settings); 

Assert.AreEqual("{\"camelCase\":1}", serialized); 
+1

不認爲序列化+反序列化+序列化過於高效。 – 2013-02-27 11:47:14

+1

作爲解決方法我已經從JObject轉換到Dictionary 。 – 2013-02-27 11:48:04

+0

@AndreaBalducci查看我的編輯。 – 2013-02-27 19:49:06

20

這個問題從一個JObject開始,希望工作到一個駝峯式的JSON對象。如果你實際上是從一個對象開始,你想獲得到已經一個駝峯JObject,那麼你可以這樣做:

var serializer = new JsonSerializer() 
{ 
    ContractResolver = new CamelCasePropertyNamesContractResolver() 
}; 
var jo = JObject.FromObject(someDataContract, serializer); 

產生的「JO」,將駝峯格式。

+1

這應該是被接受的答案。 – ssougnez 2017-03-22 16:38:24

+0

如何執行相反的操作:'JObject.Load(jsonReader)'指定解析器? – Shimmy 2017-12-07 00:16:56

3

this截止到2013年5月8日,James Newton-King發佈了關於Json.NET 5.0版本的博客文章,其中增加了「DefaultSettings」。該頁面的示例如下,但閱讀第三方庫的詳細信息頁面。

// settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject 
JsonConvert.DefaultSettings =() => new JsonSerializerSettings 
    { 
    Formatting = Formatting.Indented, 
    ContractResolver = new CamelCasePropertyNamesContractResolver() 
    }; 

Employee e = new Employee 
    { 
    FirstName = "Eric", 
    LastName = "Example", 
    BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc), 
    Department = "IT", 
    JobTitle = "Web Dude" 
    }; 

string json = JsonConvert.SerializeObject(e); 
// { 
// "firstName": "Eric", 
// "lastName": "Example", 
// "birthDate": "1980-04-20T00:00:00Z", 
// "department": "IT", 
// "jobTitle": "Web Dude" 
// }