我正在使用Json.Net框架,我正在尝试使用一种方法将多个Json字符串转换为不同的对象来实现它。
要创建存储Json数据的对象,我正在使用此website。
到目前为止,我已经设法有一个方法来转换一个对象(在本例中为RootObject
),代码如下:
public class WebService
{
protected string jsonstring;
// Other code
// Method
public RootObject stringToObject(){
return JsonConvert.DeserializeObject<RootObject>(this.jsonstring);
}
}
// Object
public class RootObject
{
public string id { get; set; }
public string name { get; set; }
public string title { get; set; }
}
// Usage
WebService ws = new WebService ("http://example.com/json_string.json");
RootObject data = ws.stringToObject ();
问题是我需要将另外两个对象转换为Json字符串:
public class RootObject2
{
public string id { get; set; }
public string menu_id { get; set; }
public string language { get; set; }
public string title { get; set; }
}
public class RootObject3
{
public string id { get; set; }
public string menu_id { get; set; }
public string position { get; set; }
public string active { get; set; }
}
我尝试将方法返回类型更改为泛型类型,但它不起作用:
public object stringToObject(){
return JsonConvert.DeserializeObject<object>(this.jsonstring);
}
如何将方法返回类型设置为动态,以便我可以执行以下操作:
WebService ws = new WebService ("http://example.com/json_string.json");
RootObject data = ws.stringToObject ();
WebService ws2 = new WebService ("http://example.com/json_string2.json");
RootObject2 data2 = ws2.stringToObject ();
WebService ws3 = new WebService ("http://example.com/json_string3.json");
RootObject3 data3 = ws3.stringToObject ();
答案 0 :(得分:1)
为什么不让function fold(arr1, arr2) {
var res = [];
var currIndex = 0
var otherIndex = 0
var curr = arr1
var other = arr2
var i = 0;
function switchVal() {
var tmpIndex = otherIndex
var tmp = other
otherIndex = currIndex
other = curr
curr = tmp
currIndex = tmpIndex
}
do {
var indexInOther = other.indexOf(curr[currIndex], otherIndex)
if (indexInOther >= 0) {
var prevItems = other.slice(otherIndex, indexInOther + 1)
res = res.concat(prevItems)
otherIndex = indexInOther + 1
currIndex++
switchVal()
} else if (currIndex < curr.length) {
res.push(curr[currIndex])
currIndex++
} else {
switchVal()
}
} while(currIndex < curr.length || otherIndex < other.length)
return res
}
成为generic?
WebService
然后做
public class WebService<T>
{
protected string jsonstring;
// Other code
// Method
public T stringToObject(){
return JsonConvert.DeserializeObject<T>(this.jsonstring);
}
}
或者,如果您愿意,可以将var ws = new WebService<RootObject>("http://example.com/json_string.json");
var data = ws.stringToObject ();
设为通用:
stringToObject
并做:
public class WebService
{
protected string jsonstring;
// Other code
// Method
public T stringToObject<T>(){
return JsonConvert.DeserializeObject<T>(this.jsonstring);
}
}