本文整理汇总了C#中Newtonsoft.Json.Linq.JObject.TryGetValue方法的典型用法代码示例。如果您正苦于以下问题:C# JObject.TryGetValue方法的具体用法?C# JObject.TryGetValue怎么用?C# JObject.TryGetValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Newtonsoft.Json.Linq.JObject
的用法示例。
在下文中一共展示了JObject.TryGetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetTypeFromJObject
private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
{
JToken typeToken;
serializer.TypeNameHandling = TypeNameHandling.None;
if (po.TryGetValue("type", out typeToken))
{
var type = typeToken.Value<string>().ToLowerInvariant();
switch (type)
{
case "string":
return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
case "float":
case "double":
case "byte":
case "short":
case "integer":
case "long":
return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
case "date":
return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
case "boolean":
return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
case "binary":
return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
}
}
return null;
}
示例2: Set
/// <summary>
/// Create or change some settings
/// </summary>
/// <param name="newSettings">The object containing the new settings</param>
/// <returns></returns>
public HttpResponseMessage Set(JObject newSettings)
{
if (newSettings == null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
// We support two formats here:
// 1. For backward compat, we support {key: 'someKey', value: 'someValue' }
// 2. The preferred format is { someKey = 'someValue' }
// Note that #2 allows multiple settings to be set, e.g. { someKey = 'someValue', someKey2 = 'someValue2' }
JToken keyToken, valueToken;
if (newSettings.Count == 2 && newSettings.TryGetValue("key", out keyToken) && newSettings.TryGetValue("value", out valueToken))
{
string key = keyToken.Value<string>();
if (String.IsNullOrEmpty(key))
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
_settingsManager.SetValue(key, valueToken.Value<string>());
}
else
{
foreach (var keyValuePair in newSettings)
{
_settingsManager.SetValue(keyValuePair.Key, keyValuePair.Value.Value<string>());
}
}
return Request.CreateResponse(HttpStatusCode.NoContent);
}
示例3: FromJson
public int TotalSize { protected set; get; } // set during fetch
/// <summary>
/// Build SyncTarget from json
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static SyncDownTarget FromJson(JObject target)
{
if (target == null) return null;
JToken impl;
if (target.TryGetValue(WindowsImpl, out impl))
{
JToken implType;
if (target.TryGetValue(WindowsImplType, out implType))
{
try
{
Assembly assembly = Assembly.Load(new AssemblyName(impl.ToObject<string>()));
Type type = assembly.GetType(implType.ToObject<string>());
if (type.GetTypeInfo().IsSubclassOf(typeof(SyncTarget)))
{
MethodInfo method = type.GetTypeInfo().GetDeclaredMethod("FromJson");
return (SyncDownTarget)method.Invoke(type, new object[] { target });
}
}
catch (Exception)
{
throw new SmartStoreException("Invalid SyncDownTarget");
}
}
}
throw new SmartStoreException("Could not generate SyncDownTarget from json target");
}
示例4: TermDefinition
public TermDefinition(JObject obj)
{
JToken id;
if (obj.TryGetValue("@id", out id))
{
Id = id.ToString();
}
JToken type;
if (obj.TryGetValue("@type", out type))
{
Type = type.ToString();
}
JToken language;
if (obj.TryGetValue("@language", out language))
{
Language = language.ToString();
}
JToken container;
if (obj.TryGetValue("@container", out container))
{
Container = container.ToString();
}
JToken reverse;
if (obj.TryGetValue("@reverse", out reverse))
{
Reverse = reverse.ToString();
}
}
示例5: FromJSON
public static SyncUpTarget FromJSON(JObject target)
{
if (target == null)
{
return null;
}
// Default sync up target
JToken impl;
if (target.TryGetValue(WindowsImpl, out impl))
{
JToken implType;
if (target.TryGetValue(WindowsImplType, out implType))
{
try
{
Assembly assembly = Assembly.Load(new AssemblyName(impl.ToObject<string>()));
Type type = assembly.GetType(implType.ToObject<string>());
if (type.GetTypeInfo().IsSubclassOf(typeof(SyncTarget)))
{
return new SyncUpTarget(target);
}
}
catch (Exception)
{
throw new SmartStoreException("Invalid SyncUpTarget");
}
}
}
throw new SmartStoreException("Could not generate SyncUpTarget from json target");
}
示例6: LoginResponsePacket
public LoginResponsePacket(JObject json) : base(json)
{
if(json["CMD"].ToString() != LoginRcmd)
throw new InvalidOperationException("Wrong command type.");
JToken token;
JToken user;
json.TryGetValue("User", out user);
if (user != null)
{
int type = (int) user.Value<int>("UserType");
if (type == 0)
User = user.ToObject<Client>();
else if (type == 1)
User = user.ToObject<Specialist>();
else if (type == 2)
User = user.ToObject<Administrator>();
else if (type == 0)
User = user.ToObject<User>();
}
AuthToken = json.TryGetValue("AUTHTOKEN", out token) ? token.ToString() : null;
string test = "";
}
示例7: UserWithActivityEventJObject
public static User UserWithActivityEventJObject(JObject json)
{
User user = null;
string userId = json["user"].ToString();
if (Cinderella.CinderellaCore.UserCache.ContainsKey(userId))
user = Cinderella.CinderellaCore.UserCache[userId];
else
{
user = new User();
user.ResourceId = userId;
Cinderella.CinderellaCore.UserCache[user.ResourceId] = user;
}
JToken nameValue;
if (json.TryGetValue("username", out nameValue))
{
user.Name = json["username"].ToString();
}
JToken farmValue;
if (json.TryGetValue("iconfarm", out farmValue))
{
user.Farm = json["iconfarm"].ToString();
}
JToken serverValue;
if (json.TryGetValue("iconserver", out serverValue))
{
user.Server = json["iconserver"].ToString();
}
return user;
}
示例8: ParseEndpoint
private Endpoint ParseEndpoint(JObject json, JsonSerializer serializer)
{
if (json == null)
return null;
string label = null, objectId = null;
string type = null;
JToken value;
// Parse the label
if (json.TryGetValue("label", out value) == true && value.Type != JTokenType.Null)
label = value.ToString();
// Parse the object type
if (json.TryGetValue("type", out value) == true && value.Type != JTokenType.Null)
type = value.ToString();
// Parse the object id
if (json.TryGetValue("objectid", out value) == true && value.Type != JTokenType.Null)
objectId = value.ToString();
// Parse the object
APObject obj = null;
if (json.TryGetValue("object", out value) == true && value.Type != JTokenType.Null && value.Type == JTokenType.Object)
{
using (var reader = value.CreateReader())
{
obj = serializer.Deserialize<APObject>(value.CreateReader());
}
}
if (string.IsNullOrWhiteSpace(label) == true)
throw new Exception("Endpoint label is missing.");
if (string.IsNullOrWhiteSpace(objectId) == true)
throw new Exception("Endpoint object id is missing.");
return new Endpoint(label, objectId) { Content = obj, Type = type };
}
示例9: UpdateBridgeConfigurationsWithJObject
public static void UpdateBridgeConfigurationsWithJObject(Bridge bridge, JObject configJson)
{
try
{
bridge.Name = configJson["name"].ToString();
// Version update info
bridge.Version = configJson["swversion"].ToString();
JToken updateValue;
if (configJson.TryGetValue("swupdate", out updateValue))
{
JObject updateJson = (JObject)configJson["swupdate"];
bridge.HasSoftwareUpdate = (updateJson["updatestate"].ToString() == "1");
bridge.SoftwareUpdateText = updateJson["text"].ToString();
bridge.SoftwareUpdateUrl = updateValue["url"].ToString();
}
// White list
JToken whitelistValue;
if (configJson.TryGetValue("whitelist", out whitelistValue))
{
bridge.WhiteList.Clear();
JObject whitelistJson = (JObject)configJson["whitelist"];
IList<string> appKeys = whitelistJson.Properties().Select(p => p.Name).ToList();
bridge.WhiteList.AddRange(appKeys);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
示例10: GetTypeFromJObject
private IElasticType GetTypeFromJObject(JObject po, JsonSerializer serializer)
{
JToken typeToken;
JToken propertiesToken;
JToken fieldsToken;
var type = string.Empty;
var hasType = po.TryGetValue("type", out typeToken);
if (hasType)
type = typeToken.Value<string>().ToLowerInvariant();
else if (po.TryGetValue("properties", out propertiesToken))
type = "object";
var originalType = type;
var hasFields = po.TryGetValue("fields", out fieldsToken);
if (hasFields)
type = "multi_field";
serializer.TypeNameHandling = TypeNameHandling.None;
switch (type)
{
case "string":
return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
case "float":
case "double":
case "byte":
case "short":
case "integer":
case "long":
return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
case "date":
return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
case "boolean":
return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
case "binary":
return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
case "object":
return serializer.Deserialize(po.CreateReader(), typeof(ObjectMapping)) as ObjectMapping;
case "nested":
return serializer.Deserialize(po.CreateReader(), typeof(NestedObjectMapping)) as NestedObjectMapping;
case "multi_field":
var m =serializer.Deserialize(po.CreateReader(), typeof(MultiFieldMapping)) as MultiFieldMapping;
m.Type = originalType;
return m;
case "ip":
return serializer.Deserialize(po.CreateReader(), typeof(IPMapping)) as IPMapping;
case "geo_point":
return serializer.Deserialize(po.CreateReader(), typeof(GeoPointMapping)) as GeoPointMapping;
case "geo_shape":
return serializer.Deserialize(po.CreateReader(), typeof(GeoShapeMapping)) as GeoShapeMapping;
case "attachment":
return serializer.Deserialize(po.CreateReader(), typeof(AttachmentMapping)) as AttachmentMapping;
}
return null;
}
示例11: CreateResource
static IResource CreateResource(JObject jObj, Type resourceType)
{
// remove _links and _embedded so those don't try to deserialize, because we know they will fail
JToken links;
if (jObj.TryGetValue(HalLinksName, out links))
jObj.Remove(HalLinksName);
JToken embeddeds;
if (jObj.TryGetValue(HalEmbeddedName, out embeddeds))
jObj.Remove(HalEmbeddedName);
// create value properties in base object
var resource = jObj.ToObject(resourceType) as IResource;
if (resource == null) return null;
// links are named properties, where the name is Link.Rel and the value is the rest of Link
if (links != null)
{
foreach (var rel in links.OfType<JProperty>())
CreateLinks(rel, resource);
var self = resource.Links.SingleOrDefault(l => l.Rel == "self");
if (self != null)
resource.Href = self.Href;
}
// embedded are named properties, where the name is the Rel, which needs to map to a Resource Type, and the value is the Resource
// recursive
if (embeddeds != null)
{
foreach (var prop in resourceType.GetProperties().Where(p => Representation.IsEmbeddedResourceType(p.PropertyType)))
{
// expects embedded collection of resources is implemented as an IList on the Representation-derived class
if (typeof (IEnumerable<IResource>).IsAssignableFrom(prop.PropertyType))
{
var lst = prop.GetValue(resource) as IList;
if (lst == null)
{
lst = ConstructResource(prop.PropertyType) as IList ??
Activator.CreateInstance(
typeof (List<>).MakeGenericType(prop.PropertyType.GenericTypeArguments)) as IList;
if (lst == null) continue;
prop.SetValue(resource, lst);
}
if (prop.PropertyType.GenericTypeArguments != null &&
prop.PropertyType.GenericTypeArguments.Length > 0)
CreateEmbedded(embeddeds, prop.PropertyType.GenericTypeArguments[0],
newRes => lst.Add(newRes));
}
else
{
var prop1 = prop;
CreateEmbedded(embeddeds, prop.PropertyType, newRes => prop1.SetValue(resource, newRes));
}
}
}
return resource;
}
示例12: EnsureValidSyncResponse
public static void EnsureValidSyncResponse(JObject json)
{
JToken value;
if (!json.TryGetValue("results", out value) || !(value is JArray)
|| !json.TryGetValue("deleted", out value) || !(value is JArray)
|| !json.TryGetValue("__version", out value))
{
throw new InvalidOperationException("Invalid sync response.");
}
}
示例13: DeserializeMessage
public Message DeserializeMessage(JObject messageJson)
{
JToken token = null;
if (messageJson.TryGetValue("type", out token))
{
string messageType = token.ToString();
if (string.Equals("request", messageType, StringComparison.InvariantCultureIgnoreCase))
{
return Message.Request(
messageJson.GetValue("seq").ToString(),
messageJson.GetValue("command").ToString(),
messageJson.GetValue("arguments"));
}
else if (string.Equals("response", messageType, StringComparison.InvariantCultureIgnoreCase))
{
if (messageJson.TryGetValue("success", out token))
{
// Was the response for a successful request?
if (token.ToObject<bool>() == true)
{
return Message.Response(
messageJson.GetValue("request_seq").ToString(),
messageJson.GetValue("command").ToString(),
messageJson.GetValue("body"));
}
else
{
return Message.ResponseError(
messageJson.GetValue("request_seq").ToString(),
messageJson.GetValue("command").ToString(),
messageJson.GetValue("message"));
}
}
else
{
// TODO: Parse error
}
}
else if (string.Equals("event", messageType, StringComparison.InvariantCultureIgnoreCase))
{
return Message.Event(
messageJson.GetValue("event").ToString(),
messageJson.GetValue("body"));
}
else
{
return Message.Unknown();
}
}
return Message.Unknown();
}
示例14: FromJson
public void FromJson(JObject json)
{
this.buildPath = null;
this.scenesInBuild.Clear();
this.buildTarget = (BuildTarget)0;
this.buildOptions = BuildOptions.None;
if (json == null)
{
return;
}
JToken obj;
if (json.TryGetValue("path", out obj))
{
this.buildPath = (string)obj;
}
if (json.TryGetValue("buildTarget", out obj))
{
this.buildTarget = (BuildTarget)System.Enum.Parse(typeof(BuildTarget), (string)obj, true);
}
if (json.TryGetValue("buildOptions", out obj))
{
var options = (JObject)obj;
var co = (CustomBuildOptions)this.buildOptions;
foreach (var p in options)
{
if ((bool)p.Value)
{
try
{
co |= (CustomBuildOptions)System.Enum.Parse(typeof(CustomBuildOptions), p.Key, true);
}
catch
{
}
}
}
this.buildOptions = (BuildOptions)co;
}
if (json.TryGetValue("scenes", out obj))
{
var scenes = (JArray)obj;
foreach (var s in scenes)
{
this.scenesInBuild.Add((string)s);
}
}
}
示例15: ParseEndpoints
private void ParseEndpoints(APConnection conn, JObject json, JsonSerializer serializer)
{
// Parse the endpoints
JToken value;
Endpoint ep1 = null, ep2 = null;
if (json.TryGetValue("__endpointa", out value) == true && value.Type == JTokenType.Object)
ep1 = ParseEndpoint(value as JObject, serializer);
else throw new Exception(string.Format("Endpoint A for connection with id {0} is invalid.", conn.Id));
if (json.TryGetValue("__endpointb", out value) == true && value.Type == JTokenType.Object)
ep2 = ParseEndpoint(value as JObject, serializer);
else throw new Exception(string.Format("Endpoint B for connection with id {0} is invalid.", conn.Id));
conn.Endpoints = new EndpointPair(ep1, ep2);
}