鉴于A级......
public class A {
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
string jsonString = JsonConvert.SerializeObject(
new A() {
Prop1 = "ABC",
Prop2 = "$.jqplot.DateAxisRenderer" }
);
jsonString包含... " { \" PROP1 \":\" ABC \&#34 ;, \" PROP2 \":\" $ jqplot.DateAxisRenderer \" }&#34 ;;
问题:
如何取消引用Prop2?
即。我希望jsonString包含... " { \" PROP1 \":\" ABC \&#34 ;, \" PROP2 \":$ jqplot.DateAxisRenderer }&#34 ;;
以便(在客户端)评估Prop2作为参考,不一个字符串
答案 0 :(得分:1)
如果要从Prop2中删除引号,可以为类型编写JSON.NET JsonConverter
,并将属性值输出为“raw”。
然而(这很重要),您的输出将不再是有效的JSON。
如果您对这种混合解决方案感到满意,一些示例代码如下(假设您已经在项目中引用了JSON.NET):
namespace JsonRawTest
{
public class AConverter : JsonConverter
{
public override bool CanRead { get { return false; } }
public override bool CanWrite { get { return true; } }
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
A obj = value as A;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(obj.Prop1);
writer.WritePropertyName("Prop2");
writer.WriteRawValue(obj.Prop2);
writer.WriteEndObject();
}
public override bool CanConvert(Type objectType)
{
return typeof(A).IsAssignableFrom(objectType);
}
}
public class A
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var a = new A
{
Prop1 = "Some first value",
Prop2 = "$.jqplot.DateAxisRenderer"
};
string json = JsonConvert.SerializeObject(a,
new JsonConverter[] { new AConverter() });
...
}
}
}
答案 1 :(得分:-2)
您可以将其作为字符串传递给客户端,然后使用eval()
函数来解析字符串,如下所示:
var str = "alert('hello')";
eval(str); //This will execute the alert method.
var str2 = "(function() { return true; })()";
var returned = eval(str2); //Holds value of true