public object Deserialize(JsonValue value, JsonMapper mapper) { IList<RateLimitStatus> limits = new List<RateLimitStatus>(); JsonValue resourcesValue = value.GetValue("resources"); if (resourcesValue != null) { foreach(string resourceFamily in resourcesValue.GetNames()) { JsonValue resourceFamilyValue = resourcesValue.GetValue(resourceFamily); foreach (string resourceEndpoint in resourceFamilyValue.GetNames()) { JsonValue rateLimitValue = resourceFamilyValue.GetValue(resourceEndpoint); limits.Add(new RateLimitStatus() { ResourceFamily = resourceFamily, ResourceEndpoint = resourceEndpoint, WindowLimit = rateLimitValue.GetValue<int>("limit"), RemainingHits = rateLimitValue.GetValue<int>("remaining"), ResetTime = FromUnixTime(rateLimitValue.GetValue<long>("reset")) }); } } } return limits; }
public override object Deserialize(JsonValue json, JsonMapper mapper) { LinkedInFullProfile profile = (LinkedInFullProfile)base.Deserialize(json, mapper); profile.Associations = json.GetValueOrDefault<string>("associations", String.Empty); profile.BirthDate = DeserializeLinkedInDate(json.GetValue("dateOfBirth")); profile.ConnectionsCount = json.GetValue<int>("numConnections"); profile.Distance = json.GetValue<int>("distance"); profile.Educations = DeserializeEducations(json.GetValue("educations")); profile.Email = json.GetValueOrDefault<string>("emailAddress"); profile.Honors = json.GetValueOrDefault<string>("honors", String.Empty); profile.ImAccounts = DeserializeImAccounts(json.GetValue("imAccounts")); profile.Interests = json.GetValueOrDefault<string>("interests", String.Empty); profile.IsConnectionsCountCapped = json.GetValue<bool>("numConnectionsCapped"); JsonValue locationJson = json.GetValue("location"); profile.CountryCode = locationJson.GetValue("country").GetValue<string>("code"); profile.Location = locationJson.GetValueOrDefault<string>("name", String.Empty); profile.MainAddress = json.GetValueOrDefault<string>("mainAddress", String.Empty); profile.PhoneNumbers = DeserializePhoneNumbers(json.GetValue("phoneNumbers")); profile.Positions = DeserializePositions(json.GetValue("positions")); profile.ProposalComments = json.GetValueOrDefault<string>("proposalComments", String.Empty); profile.Recommendations = DeserializeRecommendations(json.GetValue("recommendationsReceived"), mapper); profile.RecommendersCount = json.GetValueOrDefault<int?>("numRecommenders"); profile.Specialties = json.GetValueOrDefault<string>("specialties", String.Empty); profile.TwitterAccounts = DeserializeTwitterAccounts(json.GetValue("twitterAccounts")); profile.UrlResources = DeserializeUrlResources(json.GetValue("memberUrlResources")); profile.Certifications = DeserializeCertifications(json.GetValue("certifications")); profile.Skills = DeserializeSkills(json.GetValue("skills")); profile.Publications = DeserializePublications(json.GetValue("publications")); profile.Courses = DeserializeCourses(json.GetValue("courses")); profile.Languages = DeserializeLanguages(json.GetValue("languages")); return profile; }
public object Deserialize(JsonValue json, JsonMapper mapper) { Comment comment = null; if ( json != null && !json.IsNull ) { comment = new Comment(); comment.ID = json.ContainsName("id" ) ? json.GetValue<string>("id" ) : String.Empty; comment.Message = json.ContainsName("message" ) ? json.GetValue<string>("message") : String.Empty; comment.CreatedTime = json.ContainsName("created_time") ? JsonUtils.ToDateTime(json.GetValue<string>("created_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue; comment.From = mapper.Deserialize<Reference >(json.GetValue("from" )); // 04/12/2012 Paul. Likes is a connection object, so make sure that this is not the same likes property value. // 04/15/2012 Paul. Likes can be a number or an array. JsonValue jsonLikes = json.GetValue("likes"); if ( jsonLikes != null && !jsonLikes.IsNull ) { if ( jsonLikes.IsArray ) { comment.Likes = mapper.Deserialize<List<Reference>>(jsonLikes); comment.LikesCount = (comment.Likes != null) ? comment.Likes.Count : 0; } else if ( jsonLikes.IsNumber ) { comment.LikesCount = jsonLikes.GetValue<int>(); } } } return comment; }
public object Deserialize(JsonValue json, JsonMapper mapper) { SimilarPlaces similarPlaces = new SimilarPlaces(mapper.Deserialize<IList<Place>>(json)); similarPlaces.PlacePrototype = new PlacePrototype(); similarPlaces.PlacePrototype.CreateToken = json.GetValue("result").GetValue<string>("token"); return similarPlaces; }
public object Deserialize(JsonValue value, JsonMapper mapper) { Tweet tweet = new Tweet(); tweet.ID = value.GetValue<long>("id"); tweet.Text = value.GetValue<string>("text"); JsonValue fromUserValue = value.GetValue("user"); string dateFormat; if (fromUserValue != null) { tweet.FromUser = fromUserValue.GetValue<string>("screen_name"); tweet.FromUserId = fromUserValue.GetValue<long>("id"); tweet.ProfileImageUrl = fromUserValue.GetValue<string>("profile_image_url"); dateFormat = TIMELINE_DATE_FORMAT; } else { tweet.FromUser = value.GetValue<string>("from_user"); tweet.FromUserId = value.GetValue<long>("from_user_id"); tweet.ProfileImageUrl = value.GetValue<string>("profile_image_url"); dateFormat = SEARCH_DATE_FORMAT; } tweet.CreatedAt = JsonUtils.ToDateTime(value.GetValue<string>("created_at"), dateFormat); tweet.Source = value.GetValue<string>("source"); JsonValue toUserIdValue = value.GetValue("in_reply_to_user_id"); tweet.ToUserId = (toUserIdValue != null) ? toUserIdValue.GetValue<long?>() : null; JsonValue languageCodeValue = value.GetValue("iso_language_code"); tweet.LanguageCode = (languageCodeValue != null) ? languageCodeValue.GetValue<string>() : null; JsonValue inReplyToStatusIdValue = value.GetValue("in_reply_to_status_id"); tweet.InReplyToStatusId = ((inReplyToStatusIdValue != null) && !inReplyToStatusIdValue.IsNull) ? inReplyToStatusIdValue.GetValue<long?>() : null; return tweet; }
public override object Deserialize(JsonValue json, JsonMapper mapper) { JsonValue peopleJson = json.ContainsName("people") ? json.GetValue("people") : json; LinkedInProfiles profiles = (LinkedInProfiles)base.Deserialize(peopleJson, mapper); profiles.Profiles = mapper.Deserialize<IList<LinkedInProfile>>(peopleJson); return profiles; }
public object Deserialize(JsonValue json, JsonMapper mapper) { Photo photo = null; if ( json != null && !json.IsNull ) { photo = new Photo(); photo.ID = json.ContainsName("id" ) ? json.GetValue<string>("id" ) : String.Empty; photo.Name = json.ContainsName("name" ) ? json.GetValue<string>("name" ) : String.Empty; photo.Icon = json.ContainsName("icon" ) ? json.GetValue<string>("icon" ) : String.Empty; photo.Picture = json.ContainsName("picture" ) ? json.GetValue<string>("picture" ) : String.Empty; photo.Source = json.ContainsName("source" ) ? json.GetValue<string>("source" ) : String.Empty; photo.Height = json.ContainsName("height" ) ? json.GetValue<int >("height" ) : 0; photo.Width = json.ContainsName("width" ) ? json.GetValue<int >("width" ) : 0; photo.Link = json.ContainsName("link" ) ? json.GetValue<string>("link" ) : String.Empty; photo.Position = json.ContainsName("position" ) ? json.GetValue<int >("position") : 0; photo.CreatedTime = json.ContainsName("created_time") ? JsonUtils.ToDateTime(json.GetValue<string>("created_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue; photo.UpdatedTime = json.ContainsName("updated_time") ? JsonUtils.ToDateTime(json.GetValue<string>("updated_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue; photo.From = mapper.Deserialize<Reference>(json.GetValue("from" )); photo.Place = mapper.Deserialize<Page >(json.GetValue("place")); photo.Tags = mapper.Deserialize<List<Tag>>(json.GetValue("tags" )); photo.Images = mapper.Deserialize<List<Photo.Image>>(json.GetValue("images")); if ( photo.Images != null ) { int i = 0; if ( photo.Images.Count >= 5 ) photo.OversizedImage = photo.Images[i++]; if ( photo.Images.Count >= 1 ) photo.SourceImage = photo.Images[i++]; if ( photo.Images.Count >= 2 ) photo.AlbumImage = photo.Images[i++]; if ( photo.Images.Count >= 3 ) photo.SmallImage = photo.Images[i++]; if ( photo.Images.Count >= 4 ) photo.TinyImage = photo.Images[i++]; } } return photo; }
object IJsonDeserializer.Deserialize(JsonValue json, JsonMapper mapper) { var results = new SearchResults(); var userJson = json.GetValue("auth_user"); var pagingJson = json.GetValue("paging"); var jobsJson = json.GetValue("jobs"); results.ServerTime = json.GetValueOrDefault<long>("server_time"); results.ProfileAccess = json.GetValueOrDefault<string>("profile_access"); if (userJson != null) { results.AuthUser.FirstName = userJson.GetValue<string>("first_name"); results.AuthUser.LastName = userJson.GetValue<string>("last_name"); results.AuthUser.Username = userJson.GetValue<string>("uid"); results.AuthUser.Email = userJson.GetValue<string>("mail"); results.AuthUser.TimeZone = userJson.GetValue<string>("timezone"); results.AuthUser.TimeZoneOffset = userJson.GetValue<string>("timezone_offset"); } if (pagingJson != null) { results.Paging.Count = pagingJson.GetValue<int>("count"); results.Paging.Offset = pagingJson.GetValue<int>("offset"); results.Paging.Total = pagingJson.GetValue<int>("total"); } results.Jobs = mapper.Deserialize<List<Job>>(jobsJson); return results; }
public void DeserializeUnknownType() { JsonMapper mapper = new JsonMapper(); mapper.RegisterDeserializer(typeof(Class1), new Class1Deserializer()); mapper.Deserialize<Class2>(new JsonValue()); }
public object Deserialize(JsonValue json, JsonMapper mapper) { var job = new Job(); var clientJson = json.GetValue("client"); job.Id = json.GetValueOrDefault<string>("id", ""); job.Title = json.GetValueOrDefault<string>("title", ""); job.Snippet = json.GetValueOrDefault<string>("snippet", ""); job.Skills = deserializeSkills(json.GetValues("skills")); job.Category = json.GetValueOrDefault<string>("category", ""); job.Subcategory = json.GetValueOrDefault<string>("subcategory", ""); job.JobType = json.GetValueOrDefault<string>("job_type", ""); job.Duration = json.GetValueOrDefault<string>("duration", ""); job.Budget = json.GetValueOrDefault<string>("budget", ""); job.Workload = json.GetValueOrDefault<string>("workload", ""); job.Status = json.GetValueOrDefault<string>("job_status", ""); job.Url = json.GetValueOrDefault<string>("url", ""); job.DateCreated = json.GetValueOrDefault<DateTime>("date_created", DateTime.MinValue); if (clientJson != null) { job.Client.Country = clientJson.GetValueOrDefault<string>("country", ""); job.Client.FeedbackRating = clientJson.GetValueOrDefault<float>("feedback", 0); job.Client.ReviewCount = clientJson.GetValueOrDefault<int>("reviews_count", 0); job.Client.JobCount = clientJson.GetValueOrDefault<int>("jobs_posted", 0); job.Client.HireCount = clientJson.GetValueOrDefault<int>("past_hires", 0); job.Client.PaymentVerificationStatus = clientJson.GetValueOrDefault<string>("payment_verification_status", ""); } return job; }
public object Deserialize(JsonValue value, JsonMapper mapper) { return new DropboxLink() { Url = value.GetValue<string>("url"), ExpireDate = JsonUtils.ToDropboxDateTime(value.GetValue<string>("expires")).Value }; }
public void SetUp() { JsonMapper mapper = new JsonMapper(); mapper.RegisterDeserializer(typeof(CustomClass1), new CustomClass1Deserializer()); mapper.RegisterSerializer(typeof(CustomClass2), new CustomClass2Serializer()); converter = new SpringJsonHttpMessageConverter(mapper); }
public object Deserialize(JsonValue value, JsonMapper mapper) { return new FileRef() { Value = value.GetValue<string>("copy_ref"), ExpireDate = JsonUtils.ToDropboxDateTime(value.GetValue<string>("expires")).Value }; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<Tweet> tweets = new List<Tweet>(); foreach (JsonValue itemValue in value.GetValues()) { tweets.Add(mapper.Deserialize<Tweet>(itemValue)); } return tweets; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<Entry> entries = new List<Entry>(); foreach (JsonValue itemValue in value.GetValues()) { entries.Add(mapper.Deserialize<Entry>(itemValue)); } return entries; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<UserList> userLists = new List<UserList>(); foreach (JsonValue itemValue in value.GetValues()) { userLists.Add(mapper.Deserialize<UserList>(itemValue)); } return userLists; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<long> longs = new List<long>(); foreach (JsonValue itemValue in value.GetValues()) { longs.Add(itemValue.GetValue<long>()); } return longs; }
public object Deserialize(JsonValue json, JsonMapper mapper) { JsonValue values = json.GetValue("values"); return new NetworkStatistics() { FirstDegreeCount = values.GetValue<int>(0), SecondDegreeCount = values.GetValue<int>(1), }; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<SavedSearch> savedSearches = new List<SavedSearch>(); foreach (JsonValue itemValue in value.GetValues()) { savedSearches.Add(mapper.Deserialize<SavedSearch>(itemValue)); } return savedSearches; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<DirectMessage> directMessages = new List<DirectMessage>(); foreach (JsonValue itemValue in value.GetValues()) { directMessages.Add(mapper.Deserialize<DirectMessage>(itemValue)); } return directMessages; }
public object Deserialize(JsonValue value, JsonMapper mapper) { return new RateLimitStatus() { HourlyLimit = value.GetValue<int>("hourly_limit"), RemainingHits = value.GetValue<int>("remaining_hits"), ResetTime = JsonUtils.ToDateTime(value.GetValue<string>("reset_time"), RATE_LIMIT_STATUS_DATE_FORMAT) }; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<Place> places = new List<Place>(); foreach (JsonValue itemValue in value.GetValue("result").GetValues("places")) { places.Add(mapper.Deserialize<Place>(itemValue)); } return places; }
public object Deserialize(JsonValue value, JsonMapper mapper) { return new SearchResults() { Tweets = mapper.Deserialize<IList<Tweet>>(value.GetValue("results")), MaxId = value.GetValue<long>("max_id"), SinceId = value.GetValue<long>("since_id") }; }
public virtual object Deserialize(JsonValue json, JsonMapper mapper) { PaginatedResult paginatedResult = this.CreatePaginatedResult(); paginatedResult.Total = json.GetValue<int>("_total"); paginatedResult.Start = json.GetValueOrDefault<int>("_start", 0); paginatedResult.Count = json.GetValueOrDefault<int>("_count", paginatedResult.Total); return paginatedResult; }
public object Deserialize(JsonValue value, JsonMapper mapper) { IList<TwitterProfile> twitterProfiles = new List<TwitterProfile>(); JsonValue usersValue = value.IsObject ? value.GetValue("users") : value; foreach (JsonValue itemValue in usersValue.GetValues()) { twitterProfiles.Add(mapper.Deserialize<TwitterProfile>(itemValue)); } return twitterProfiles; }
public virtual object Deserialize(JsonValue json, JsonMapper mapper) { PaginatedResult paginatedResult = this.CreatePaginatedResult(); paginatedResult.Total = json.GetValue<int>("_total"); paginatedResult.Start = json.ContainsName("_start") ? json.GetValue<int>("_start") : 0; paginatedResult.Count = json.ContainsName("_count") ? json.GetValue<int>("_count") : paginatedResult.Total; return paginatedResult; }
public object Deserialize(JsonValue value, JsonMapper mapper) { JsonValue searchMetadataValue = value.GetValue("search_metadata"); return new SearchResults() { Tweets = mapper.Deserialize<IList<Tweet>>(value.GetValue("statuses")), MaxId = searchMetadataValue.GetValue<long>("max_id"), SinceId = searchMetadataValue.GetValue<long>("since_id") }; }
public void SerializeKnownType() { JsonMapper mapper = new JsonMapper(); mapper.RegisterSerializer(typeof(Class2), new Class2Serializer()); Class2 obj2 = new Class2(); obj2.ID = 7; JsonValue value2 = mapper.Serialize(obj2); Assert.IsNotNull(value2); Assert.AreEqual(7, value2.GetValue<long>("ID")); }
public object Deserialize(JsonValue json, JsonMapper mapper) { FacebookProfile profile = null; if ( json != null && !json.IsNull ) { profile = new FacebookProfile(); // 04/14/2012 Paul. Should not have both id and uid. profile.ID = json.ContainsName("id" ) ? json.GetValue<string>("id" ) : String.Empty; profile.ID = json.ContainsName("uid" ) ? json.GetValue<string>("uid" ) : profile.ID; profile.Username = json.ContainsName("username" ) ? json.GetValue<string>("username" ) : String.Empty; profile.Name = json.ContainsName("name" ) ? json.GetValue<string>("name" ) : String.Empty; profile.FirstName = json.ContainsName("first_name" ) ? json.GetValue<string>("first_name" ) : String.Empty; profile.LastName = json.ContainsName("last_name" ) ? json.GetValue<string>("last_name" ) : String.Empty; profile.Gender = json.ContainsName("gender" ) ? json.GetValue<string>("gender" ) : String.Empty; profile.Locale = json.ContainsName("locate" ) ? json.GetValue<string>("locate" ) : String.Empty; profile.MiddleName = json.ContainsName("middle_name" ) ? json.GetValue<string>("middle_name" ) : String.Empty; // 04/14/2012 Paul. Should not have both email and contact_email. profile.Email = json.ContainsName("email" ) ? json.GetValue<string>("email" ) : String.Empty; profile.Email = json.ContainsName("contact_email" ) ? json.GetValue<string>("contact_email" ) : profile.Email; profile.Link = json.ContainsName("link" ) ? json.GetValue<string>("link" ) : String.Empty; profile.ThirdPartyId = json.ContainsName("third_party_id" ) ? json.GetValue<string>("third_party_id" ) : String.Empty; profile.Timezone = json.ContainsName("timezone" ) ? json.GetValue<int >("timezone" ) : 0; profile.Verified = json.ContainsName("verified" ) ? json.GetValue<bool >("verified" ) : false; profile.About = json.ContainsName("about" ) ? json.GetValue<string>("about" ) : String.Empty; profile.About = json.ContainsName("about_me" ) ? json.GetValue<string>("about_me" ) : profile.About; profile.Bio = json.ContainsName("bio" ) ? json.GetValue<string>("bio" ) : String.Empty; profile.Religion = json.ContainsName("religion" ) ? json.GetValue<string>("religion" ) : String.Empty; profile.Political = json.ContainsName("political" ) ? json.GetValue<string>("political" ) : String.Empty; profile.Quotes = json.ContainsName("quotes" ) ? json.GetValue<string>("quotes" ) : String.Empty; profile.RelationshipStatus = json.ContainsName("relationship_status") ? json.GetValue<string>("relationship_status") : String.Empty; profile.Website = json.ContainsName("website" ) ? json.GetValue<string>("website" ) : String.Empty; // http://developers.facebook.com/docs/reference/fql/user/ // The birthday of the user being queried. The format of this date varies based on the user's locale. profile.Birthday = json.ContainsName("birthday" ) ? JsonUtils.ToDateTime(json.GetValue<string>("birthday" ), "MM/dd/yyyy" ) : DateTime.MinValue; // The birthday of the user being queried in MM/DD/YYYY format. profile.Birthday = json.ContainsName("birthday_date" ) ? JsonUtils.ToDateTime(json.GetValue<string>("birthday_date"), "MM/dd/yyyy" ) : profile.Birthday; profile.UpdatedTime = json.ContainsName("updated_time" ) ? JsonUtils.ToDateTime(json.GetValue<string>("updated_time" ), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue; profile.Location = mapper.Deserialize<Reference >(json.GetValue("location" )); profile.Hometown = mapper.Deserialize<Reference >(json.GetValue("hometown" )); if ( json.ContainsName("hometown_location") ) profile.Hometown = mapper.Deserialize<Reference>(json.GetValue("hometown_location")); profile.SignificantOther = mapper.Deserialize<Reference >(json.GetValue("significant_other" )); profile.Work = mapper.Deserialize<List<WorkEntry >>(json.GetValue("work" )); profile.Education = mapper.Deserialize<List<EducationEntry>>(json.GetValue("education" )); profile.InterestedIn = mapper.Deserialize<List<String >>(json.GetValue("interested_in" )); profile.InspirationalPeople = mapper.Deserialize<List<Reference >>(json.GetValue("inspirational_people")); profile.Languages = mapper.Deserialize<List<Reference >>(json.GetValue("languages" )); profile.Sports = mapper.Deserialize<List<Reference >>(json.GetValue("sports" )); profile.FavoriteTeams = mapper.Deserialize<List<Reference >>(json.GetValue("favorite_teams" )); profile.FavoriteAtheletes = mapper.Deserialize<List<Reference >>(json.GetValue("favorite_athletes" )); } return profile; }
public object Deserialize(JsonValue value, JsonMapper mapper) { return new SavedSearch() { ID = value.GetValue<long>("id"), Name = value.GetValue<string>("name"), Query = value.GetValue<string>("query"), CreatedAt = JsonUtils.ToDateTime(value.GetValue<string>("created_at"), SAVED_SEARCH_DATE_FORMAT), Position = value.GetValue<int>("position") }; }
void Init() { PlayerInfo playerInfo = new PlayerInfo { id = 1001, name = "lfwu", buffList = new List <Buff> { new Buff { id = 1001001, description = "this buff can reduce speed", baseAttack = 20.0, canRepeat = false }, new Buff { id = 1001002, description = "this buff can increase physic attack", baseAttack = 0, canRepeat = true } } }; string litJsonStr = string.Empty; string unityJsonStr = string.Empty; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); int count = 1000; sw.Start(); for (var i = 0; i < count; ++i) { litJsonStr = JsonMapper.ToJson(playerInfo); } Debug.Log("LitJson Serialize use time:" + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (var i = 0; i < count; ++i) { unityJsonStr = JsonUtility.ToJson(playerInfo); } Debug.Log("UnityJson Serialize use time:" + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (var i = 0; i < count; ++i) { PlayerInfo litPlayerInfo = JsonMapper.ToObject <PlayerInfo>(litJsonStr); } Debug.Log("LitJson Deserialzie use time:" + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (var i = 0; i < count; ++i) { PlayerInfo unityJsonInfo = JsonUtility.FromJson <PlayerInfo>(litJsonStr); } Debug.Log("UnityJson Deserialize use time:" + sw.ElapsedMilliseconds); Debug.Log("unity string len:" + unityJsonStr.Length + ", litjson string len:" + litJsonStr.Length); }
void Start() { itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.json")); ConstructItemDatabase(); }
public static object FromJson(Type type, string str) { return(JsonMapper.ToObject(type, str)); }
IEnumerator TakeLeaderBoardData() { OverallScrollBar.SetActive(true); GradeScrollBar.SetActive(false); SchoolScrollBar.SetActive(false); if (PrenetOject.childCount == 0) { string Hitting_Url = MainUrl + LeaderBoardApi + "?id_user="******"UID") + "&org_id=" + PlayerPrefs.GetInt("OID"); WWW Leaderborad_url = new WWW(Hitting_Url); yield return(Leaderborad_url); if (Leaderborad_url.text != null) { Debug.Log(Leaderborad_url.text); JsonData leader_res = JsonMapper.ToObject(Leaderborad_url.text); for (int a = 0; a < leader_res.Count; a++) { GameObject gb = Instantiate(Dataprefeb, PrenetOject, false); if (int.Parse(leader_res[a]["Rank"].ToString()) == 1) { gb.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject.SetActive(true); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(false); gb.transform.GetChild(0).gameObject.transform.GetChild(0).GetComponent <Image>().sprite = FirstRank; } else if (int.Parse(leader_res[a]["Rank"].ToString()) == 2) { gb.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject.SetActive(true); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(false); gb.transform.GetChild(0).gameObject.transform.GetChild(0).GetComponent <Image>().sprite = SecondRank; } else if (int.Parse(leader_res[a]["Rank"].ToString()) == 3) { gb.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject.SetActive(true); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(false); gb.transform.GetChild(0).gameObject.transform.GetChild(0).GetComponent <Image>().sprite = ThirdRank; } else if (int.Parse(leader_res[a]["Rank"].ToString()) == 0) { gb.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject.SetActive(false); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(true); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.GetComponent <Text>().text = leader_res[a]["Rank"].ToString(); } else { gb.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject.SetActive(false); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(true); gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.GetComponent <Text>().text = leader_res[a]["Rank"].ToString(); } if (PlayerPrefs.GetInt("UID") == int.Parse(leader_res[a]["id_user"].ToString())) { gb.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.GetComponent <Text>().color = MydataColor; gb.transform.GetChild(2).gameObject.GetComponent <Text>().color = MydataColor; gb.transform.GetChild(3).gameObject.GetComponent <Text>().color = MydataColor; gb.transform.GetChild(4).gameObject.GetComponent <Text>().color = MydataColor; gb.transform.GetChild(5).gameObject.GetComponent <Text>().color = MydataColor; gb.transform.GetChild(6).gameObject.GetComponent <Image>().enabled = false; gb.transform.GetChild(6).gameObject.transform.GetChild(0).GetComponent <Text>().color = MydataColor; gb.GetComponent <BarHeighter>().heighlitedimage = RowHighlighter; gb.GetComponent <BarHeighter>().normalimage = RowHighlighter; gb.GetComponent <Image>().sprite = RowHighlighter; } gb.SetActive(true); if (leader_res[a]["Name"] != null) { gb.transform.GetChild(2).gameObject.GetComponent <Text>().text = leader_res[a]["Name"].ToString(); } if (leader_res[a]["Level"] != null) { gb.transform.GetChild(4).gameObject.GetComponent <Text>().text = leader_res[a]["Level"].ToString(); } else { gb.transform.GetChild(4).gameObject.GetComponent <Text>().text = "0"; } if (leader_res[a]["Grade"] != null) { gb.transform.GetChild(5).gameObject.GetComponent <Text>().text = leader_res[a]["Grade"].ToString(); } else { gb.transform.GetChild(5).gameObject.GetComponent <Text>().text = "0"; } if (leader_res[a]["SchoolName"] != null) { gb.transform.GetChild(3).gameObject.GetComponent <Text>().text = leader_res[a]["SchoolName"].ToString(); } else { gb.transform.GetChild(3).gameObject.GetComponent <Text>().text = "----"; } if (leader_res[a]["Score"] != null) { gb.transform.GetChild(6).gameObject.transform.GetChild(0).GetComponent <Text>().text = leader_res[a]["Score"].ToString(); } else { gb.transform.GetChild(6).gameObject.transform.GetChild(0).GetComponent <Text>().text = "0"; } UserlistCreated.Add(gb); } } } }
//处理ERRORCODE int GetErrorCode(string _jsonText) { JsonData data = JsonMapper.ToObject(_jsonText); return((int)data["errorcode"]); }
void linkageWallet(Dictionary <string, string> parameters, string channel) { string request = parameters ["request"]; string nonce = System.Guid.NewGuid() + "";; Dictionary <string, string> newParameters = new Dictionary <string, string>(); newParameters.Add("channel", channel); newParameters.Add("nonce", nonce); newParameters.Add("x-success", urlscheme); if (request == "sign") { newParameters.Add("unsigned_hex", parameters["unsigned_hex"]); } string jsonString = JsonMapper.ToJson(newParameters); string urlParams = request + "?params=" + jsonString; if (request == "getaddress" || request == "verifyuser") { string xcallback_params = "channel=" + channel + "&nonce=" + nonce + "&x-success=" + urlscheme + "&msg=" + channel; urlParams = "x-callback-url/" + request + "?" + xcallback_params; } Debug.Log("urlparams: " + urlParams); bool fail = false; #if UNITY_IPHONE Application.OpenURL("indiewallet://" + urlParams); #elif UNITY_ANDROID AndroidJavaClass up = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject ca = up.GetStatic <AndroidJavaObject> ("currentActivity"); AndroidJavaObject packageManager = ca.Call <AndroidJavaObject> ("getPackageManager"); AndroidJavaObject launchIntent = null; launchIntent = packageManager.Call <AndroidJavaObject> ("getLaunchIntentForPackage", "inc.lireneosoft.counterparty"); launchIntent.Call <AndroidJavaObject> ("setClassName", "inc.lireneosoft.counterparty", "inc.lireneosoft.counterparty.IntentActivity"); try { AndroidJavaClass Uri = new AndroidJavaClass("android.net.Uri"); AndroidJavaObject uri = Uri.CallStatic <AndroidJavaObject>("parse", "indiewallet://" + urlParams); launchIntent.Call <AndroidJavaObject> ("setData", uri); //launchIntent.Call<AndroidJavaObject>("setAction", "inc.lireneosoft.counterparty.IntentActivity"); launchIntent.Call <AndroidJavaObject>("putExtra", "source", urlParams); } catch (System.Exception e) { fail = true; } if (fail) { Debug.Log("app not found"); } else { ca.Call("startActivity", launchIntent); } up.Dispose(); ca.Dispose(); packageManager.Dispose(); launchIntent.Dispose(); #else string qrurl = "indiewallet://" + urlParams; IndieCoreResult result = new IndieCoreResult(); result.error = null; result.method = currentMethod; result.result = qrurl; result.qrcode = generateQR(qrurl); indieCoreCallback(result); #endif }
public static string ToJson <T>(T t) { return(JsonMapper.ToJson(t)); }
//-----------------end of extension of game-mode //---------------- helpers public string ToJson() { var str = JsonMapper.ToJson(this); return(str); }
public static Map FromJson(string json) { var ret = JsonMapper.ToObject <Map>(json); return(ret); }
private void OnGUI() { if (GUI.Button(new Rect(50, 50, 50, 50), "test")) { AutoActionContainer container = new AutoActionContainer(); AutoLoadScene loadScene = new AutoLoadScene("test"); AutoClick click = new AutoClick(new Vector3(10, 20, 30)); AutoTimer timer = new AutoTimer(5); AutoPressUI pressUI = new AutoPressUI("bg"); container.AddAction(loadScene); container.AddAction(click); container.AddAction(timer); container.AddAction(pressUI); AutoActionContainer container2 = new AutoActionContainer(); AutoWaitObjectAppear objectAppear = new AutoWaitObjectAppear("page"); AutoWaitObjectAppear objectDisappear = new AutoWaitObjectAppear("pageDis"); AutoWaitComponentAppear componentAppear = new AutoWaitComponentAppear(typeof(Image)); AutoWaitComponentDisappear componentDisappear = new AutoWaitComponentDisappear(typeof(Button)); AutoLabelTextAppear labelText = new AutoLabelTextAppear("label", "hello world"); container2.AddAction(container); container2.AddAction(objectAppear); container2.AddAction(labelText); container2.AddAction(objectDisappear); container2.AddAction(componentAppear); container2.AddAction(componentDisappear); string json = AutoActionJsonWriter.Write(container2); Debug.Log("json is:" + json); JsonData data = JsonMapper.ToObject(json); AutoActionContainer newContainer = AutoActionJsonParser.Parse(data) as AutoActionContainer; foreach (AutoAction action in newContainer.ActionList) { Debug.Log(action.GetType().Name); if (action.GetType().Name == "AutoActionContainer") { foreach (AutoAction childAction in (action as AutoActionContainer).ActionList) { Debug.Log(childAction.GetType().Name); } } } } }
// POST: api/Account public RetValue Post([FromBody] string jsonStr) { RetValue ret = new RetValue(); JsonData jsonData = JsonMapper.ToObject(jsonStr); //时间戳 long t = Convert.ToInt64(jsonData["t"].ToString()); string deviceIdentifier = jsonData["deviceIdentifier"].ToString(); string deviceModel = jsonData["deviceModel"].ToString(); string sign = jsonData["sign"].ToString(); //1.判断时间戳 如果大于3秒 直接返回错误 if (MFDSAUtil.GetTimestamp() - t > 3) { ret.HasError = true; ret.ErrorCode = ProtoCode.RequestDelay;//"url请求无效"; return(ret); } //2.验证签名 string signServer = MFEncryptUtil.Md5(string.Format("{0}:{1}", t, deviceIdentifier)); if (!signServer.Equals(sign, StringComparison.CurrentCultureIgnoreCase)) { ret.HasError = true; ret.ErrorCode = ProtoCode.SignatureInvalid;//"签名无效"; return(ret); } int type = Convert.ToInt32(jsonData["Type"].ToString()); string userName = jsonData["UserName"].ToString(); string pwd = jsonData["Pwd"].ToString(); if (type == 0) { short channelId = jsonData["ChannelId"].ToString().ToShort(); //注册 MFReturnValue <int> retValue = AccountCacheModel.Instance.Register(userName, pwd, channelId, deviceIdentifier, deviceModel); ret.HasError = retValue.HasError; //ret.ErrorMsg = retValue.Message; ret.ErrorCode = ProtoCode.AccountRegistrationFailed; int userID = retValue.Value; AccountEntity entity = AccountCacheModel.Instance.GetEntity(userID); ret.Value = JsonMapper.ToJson(new RetAccountEntity(entity)); } else { //登录 AccountEntity entity = AccountCacheModel.Instance.LogOn(userName, pwd, deviceIdentifier, deviceModel); if (entity != null) { ret.Value = JsonMapper.ToJson(new RetAccountEntity(entity)); } else { ret.HasError = true; ret.ErrorCode = ProtoCode.AccountDoesNotExist; //"帐户不存在"; } } return(ret); }
public static T FromJson <T>(string str) { return(JsonMapper.ToObject <T>(str)); }
/// <summary> /// 将对象序列化为 JSON 字符串 /// </summary> /// <param name="obj">要序列化的对象</param> /// <returns>序列化后的 JSON 字符串</returns> public string ToJson(object obj) { return(JsonMapper.ToJson(obj)); }
/// <summary> /// 设置新配置 /// </summary> /// <param name="gameConfig"></param> public void SetNewConfig(string gameConfig) { this.Data = JsonMapper.ToObject <GameConfig>(gameConfig); }
/// <summary> /// 导出数据 /// </summary> /// <param name="fileName"></param> private void OnExportData(string fileName) { GameObject root_scene = getSceneRoot(); GameObject root_map = getMapRoot(); GameObject light = GameObject.Find(light_name); GameObject ui_root = GameObject.Find(ui_name); if (light == null) { Debug.LogError("没有添加方向光"); return; } if (ui_root == null) { Debug.LogError("没有添加摄像机"); return; } SceneConf conf_scene = new SceneConf() { //Trans = root_scene.transform, Map = new MapConf() { // Trans = root_map.transform, Ground = new GroundConf(), Surface = new SurfaceConf(), }, Light = new PrefabConf() { PrefabName = light_name }, UI = new PrefabConf() { PrefabName = ui_name } }; conf_scene.SetTransform(root_scene.transform); conf_scene.Map.SetTransform(root_map.transform); conf_scene.Light.SetTransform(light.transform); conf_scene.UI.SetTransform(ui_root.transform.FindChild("Camera")); //序列化小怪位置数据 Transform placeholder_root_trans = getPlaceHolderRoot(); conf_scene.PlaceHolder = new List <PlaceHolderConfig>(); for (int i = 0; i < placeholder_root_trans.childCount; i++) { PlaceHolderConfig v_point = new PlaceHolderConfig(); v_point.SetTransform(placeholder_root_trans.GetChild(i), false); conf_scene.PlaceHolder.Add(v_point); } //序列化Bounds数据 Transform bounds_root_trans = BoundsRoot; int bounds_point_count = bounds_root_trans.childCount; conf_scene.Bounds = new List <BoundsConfig>(); List <Transform> bounds_points_list = new List <Transform>(); for (int i = 0; i < bounds_point_count; i++) { Transform bounds_points_trans = bounds_root_trans.GetChild(i); bounds_points_list.Add(bounds_points_trans); } //按照字符串排序 var bounds_points_sorted = from point in bounds_points_list orderby point.name ascending select point; foreach (var item in bounds_points_sorted) { BoundsConfig v_point = new BoundsConfig(); v_point.SetTransform(item); conf_scene.Bounds.Add(v_point); } //序列化ground数据 Transform ground_root_trans = root_map.transform.FindChild(ground_root_name); if (ground_root_trans != null) { List <GroundCell> cells = new List <GroundCell>(); float w = 1, h = 1; int gournd_cell_count = ground_root_trans.childCount; if (gournd_cell_count > 0) { Mesh mesh = ground_root_trans.GetChild(0).GetComponent <MeshFilter>().sharedMesh; w = mesh.bounds.size.x; h = mesh.bounds.size.z; //Debug.Log(mesh.vertices[0] + "," + mesh.vertices[1] + "," + mesh.vertices[2] + "," + mesh.vertices[3]); } for (int i = 0; i < gournd_cell_count; i++) { GroundCell cell = new GroundCell(); // cell.Trans = ground_root_trans.GetChild(i); Transform item_trans = ground_root_trans.GetChild(i); cell.SetTransform(item_trans); List <string> mats = new List <string>(); Material[] mat = item_trans.GetComponent <MeshRenderer>().sharedMaterials; if (mat != null && mat.Length > 0) { for (int j = 0; j < mat.Length; j++) { if (mat[j] != null) { mats.Add(mat[j].name); } } } cell.Materials = mats; cells.Add(cell); } conf_scene.Map.Ground.SetTransform(ground_root_trans); conf_scene.Map.Ground.GroundCells = cells; conf_scene.Map.Ground.CellWidth = w; conf_scene.Map.Ground.CellHeight = h; } else { EditorUtility.DisplayDialog("提示", "亲,还没创建地图!", "确认"); return; } //序列化surface数据 Transform surface_root_trans = root_map.transform.FindChild(surface_root_name); if (surface_root_trans != null) { conf_scene.Map.Surface.SetTransform(surface_root_trans); List <SurfaceCellCollider> element_colliders = new List <SurfaceCellCollider>(); List <SurfaceCellPlaneWithCollider> element_planeWithColliders = new List <SurfaceCellPlaneWithCollider>(); List <SurfaceCellPlane> element_planes = new List <SurfaceCellPlane>(); for (int i = 0; i < surface_root_trans.childCount; i++) { Transform item_trans = surface_root_trans.GetChild(i); string name_post_fix = item_trans.name.Substring(item_trans.gameObject.name.LastIndexOf('_') + 1); if (name_post_fix.Equals("pc")) { SurfaceCellPlaneWithCollider cell = new SurfaceCellPlaneWithCollider(); cell.SetTransform(item_trans); List <string> mats = new List <string>(); Material[] mat = item_trans.gameObject.GetComponent <MeshRenderer>().sharedMaterials; if (mat != null && mat.Length > 0) { for (int j = 0; j < mat.Length; j++) { if (mat[j] != null) { mats.Add(mat[j].name); } } } cell.Plane = new SurfaceCellPlane() { Materials = mats }; cell.Plane.CellWidth = item_trans.GetComponent <MeshFilter>().sharedMesh.bounds.size.x; cell.Plane.CellHeight = item_trans.GetComponent <MeshFilter>().sharedMesh.bounds.size.z; List <SurfaceCellCollider> colliders = new List <SurfaceCellCollider>(); for (int j = 0; j < item_trans.childCount; j++) { Transform item_item_trans = item_trans.GetChild(j); SurfaceCellCollider cell_col = new SurfaceCellCollider(); cell_col.SetTransform(item_item_trans); BoxCollider col = item_item_trans.GetComponent <BoxCollider>(); cell_col.Center = cell_col.Vector3ToList(col.center); cell_col.Size = cell_col.Vector3ToList(col.size); cell_col.IsTrigger = col.isTrigger; colliders.Add(cell_col); } cell.Colliders = colliders; element_planeWithColliders.Add(cell); } else if (name_post_fix.Equals("p")) { SurfaceCellPlane cell = new SurfaceCellPlane(); cell.SetTransform(item_trans); List <string> mats = new List <string>(); Material[] mat = item_trans.gameObject.GetComponent <MeshRenderer>().sharedMaterials; if (mat != null && mat.Length > 0) { for (int j = 0; j < mat.Length; j++) { if (mat[j] != null) { mats.Add(mat[j].name); } } } cell.Materials = mats; Mesh mesh = item_trans.GetComponent <MeshFilter>().sharedMesh; cell.CellWidth = mesh.bounds.size.x; cell.CellHeight = mesh.bounds.size.z; element_planes.Add(cell); } else if (name_post_fix.Equals("c")) { SurfaceCellCollider cell = new SurfaceCellCollider(); cell.SetTransform(item_trans); BoxCollider col = item_trans.GetComponent <BoxCollider>(); cell.Center = cell.Vector3ToList(col.center); cell.Size = cell.Vector3ToList(col.size); cell.IsTrigger = col.isTrigger; element_colliders.Add(cell); } } conf_scene.Map.Surface.Colliders = element_colliders; conf_scene.Map.Surface.PlaneWithColliders = element_planeWithColliders; conf_scene.Map.Surface.Planes = element_planes; } string json = JsonMapper.ToJson(conf_scene); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); SceneConf obj = JsonMapper.ToObject <SceneConf>(File.ReadAllText(fileName)); bool success = json.Equals(JsonMapper.ToJson(obj)); if (success) { Debug.Log(fileName + ",导出成功!"); } else { Debug.LogError("shit,导出貌似出错了,问问程序猿吧!"); } }
//赋值常数 void LoadConst() { List <ConstData> constDataList = Util.GetList <MsgConstData, ConstData>(); foreach (ConstData data in constDataList) { string constName = Util.GetConfigString(data.name); string constValue = JsonMapper.ToObject(Util.GetConfigString(data.value))[0].ToString(); switch (constName) { case "CONST_MAX_LEVEL": Const.CONST_MAX_LEVEL = int.Parse(constValue); break; case "CONST_STAMINA_RECOVER": Const.CONST_STAMINA_RECOVER = int.Parse(constValue); break; case "CONST_STAMINA_GIFT": Const.CONST_STAMINA_GIFT = constValue; break; case "CONST_MAX_FRIEND": Const.CONST_MAX_FRIEND = int.Parse(constValue); break; case "CONST_HERO_LVUP_CONSUME": Const.CONST_HERO_LVUP_CONSUME = int.Parse(constValue); break; case "CONST_HERO_POTENTIAL_UP": Const.CONST_HERO_POTENTIAL_UP = int.Parse(constValue); break; case "CONST_HERO_POTENTIAL_COIN": Const.CONST_HERO_POTENTIAL_COIN = int.Parse(constValue); break; case "CONST_MAX_ENERGY": Const.CONST_MAX_ENERGY = int.Parse(constValue); break; case "CONST_ENERGY_RECOVER_TIME": Const.CONST_ENERGY_RECOVER_TIME = int.Parse(constValue); break; case "CONST_ENERGY_RECOVER_VAL": Const.CONST_ENERGY_RECOVER_VAL = int.Parse(constValue); break; case "CONST_MIN_ENERGY_LIMIT": Const.CONST_MIN_ENERGY_LIMIT = int.Parse(constValue); break; case "CONST_RUNE_MAX_LEVEL": Const.CONST_RUNE_MAX_LEVEL = int.Parse(constValue); break; case "CONST_RUNE_LEVEL_INTERVAL": Const.CONST_RUNE_LEVEL_INTERVAL = int.Parse(constValue); break; case "CONST_ATTACK_INTERVAL": Const.CONST_ATTACK_INTERVAL = int.Parse(constValue); break; case "CONST_BASIC_MISS_RATE": Const.CONST_BASIC_MISS_RATE = float.Parse(constValue); break; case "CONST_DODGE_FACTOR": Const.CONST_DODGE_FACTOR = float.Parse(constValue); break; case "CONST_MAX_MISS_RATE": Const.CONST_MAX_MISS_RATE = float.Parse(constValue); break; case "CONST_MIN_MISS_RATE": Const.CONST_MIN_MISS_RATE = float.Parse(constValue); break; case "CONST_BASIC_CRIT_RATE": Const.CONST_BASIC_CRIT_RATE = float.Parse(constValue); break; case "CONST_CRIT_FACTOR": Const.CONST_CRIT_FACTOR = float.Parse(constValue); break; case "CONST_MAX_CRIT_RATE": Const.CONST_MAX_CRIT_RATE = float.Parse(constValue); break; case "CONST_MIN_CRIT_RATE": Const.CONST_MIN_CRIT_RATE = float.Parse(constValue); break; case "CONST_BASIC_CRIT_DMG": Const.CONST_BASIC_CRIT_DMG = int.Parse(constValue); break; case "CONST_RESIST_FACTOR": Const.CONST_RESIST_FACTOR = float.Parse(constValue); break; case "CONST_MAX_DEF_EFFECT": Const.CONST_MAX_DEF_EFFECT = int.Parse(constValue); break; case "CONST_MIN_DEF_EFFECT": Const.CONST_MIN_DEF_EFFECT = float.Parse(constValue); break; case "CONST_DEF_FACTOR": Const.CONST_DEF_FACTOR = float.Parse(constValue); break; case "CONST_COMBO_TIME": Const.CONST_COMBO_TIME = float.Parse(constValue); break; case "CONST_SPECIALSKILL_RNDMAX": Const.CONST_SPECIALSKILL_RNDMAX = int.Parse(constValue); break; case "CONST_SPECIALSKILL_RNDMIN": Const.CONST_SPECIALSKILL_RNDMIN = int.Parse(constValue); break; case "CONST_MERCENARY_COOLDOWN": Const.CONST_MERCENARY_COOLDOWN = int.Parse(constValue); break; case "CONST_MERCENARY_TIME": Const.CONST_MERCENARY_TIME = int.Parse(constValue); break; case "CONST_MERCENARY_FEE": Const.CONST_MERCENARY_FEE = float.Parse(constValue); break; case "CONST_RUNE_EXPAND_INTERVAL": Const.CONST_RUNE_EXPAND_INTERVAL = int.Parse(constValue); break; case "CONST_MAX_SUMMON_VAL_INIT": Const.CONST_MAX_SUMMON_VAL_INIT = int.Parse(constValue); break; case "CONST_FIRST_HERO": Const.CONST_FIRST_HERO = int.Parse(constValue); break; case "CONST_DUNGEON_MAX_TIME_POINT": Const.CONST_DUNGEON_MAX_TIME_POINT = int.Parse(constValue); break; case "CONST_DUNGEON_TIME_FACTOR": Const.CONST_DUNGEON_TIME_FACTOR = float.Parse(constValue); break; case "CONST_DUNGEON_LIFE_PCT": Const.CONST_DUNGEON_LIFE_PCT = float.Parse(constValue); break; case "CONST_DUNGEON_MAX_LIFE_POINT": Const.CONST_DUNGEON_MAX_LIFE_POINT = int.Parse(constValue); break; case "CONST_DUNGEON_MAX_COMBO_POINT": Const.CONST_DUNGEON_MAX_COMBO_POINT = int.Parse(constValue); break; case "CONST_DUNGEON_COMBO_FACTOR": Const.CONST_DUNGEON_COMBO_FACTOR = float.Parse(constValue); break; case "CONST_DUNGEON_COMBO_BASIC": Const.CONST_DUNGEON_COMBO_BASIC = int.Parse(constValue); break; case "CONST_DUNGEON_TECH_BASIC": Const.CONST_DUNGEON_TECH_BASIC = int.Parse(constValue); break; case "CONST_DUNGEON_TECH_FACTOR": Const.CONST_DUNGEON_TECH_FACTOR = int.Parse(constValue); break; case "CONST_DUNGEON_DEATH_BASIC": Const.CONST_DUNGEON_DEATH_BASIC = int.Parse(constValue); break; case "CONST_DUNGEON_DEATH_FACTOR": Const.CONST_DUNGEON_DEATH_FACTOR = float.Parse(constValue); break; case "CONST_DUNGEON_SPECSKILL_FACTOR": Const.CONST_DUNGEON_SPECSKILL_FACTOR = int.Parse(constValue); break; case "CONST_DUNGEON_MAX_SPECSKILL_POINT": Const.CONST_DUNGEON_MAX_SPECSKILL_POINT = int.Parse(constValue); break; case "CONST_DUNGEON_SPECSKILL_BASIC": Const.CONST_DUNGEON_SPECSKILL_BASIC = int.Parse(constValue); break; } } }
void HandleHttpAsyncCallback(bool error, string res) { IndieCoreResult result = new IndieCoreResult(); if (error) { result.error = new IndieCoreError(res); result.method = currentMethod; result.result = null; indieCoreCallback(result); return; } if (currentMethod == "getAddress") { JsonData data = JsonMapper.ToObject(res); JsonData data1 = data ["data"]; string address = data1 ["address"].ToString(); string signature = data1 ["signature"].ToString(); if (verifySignature(address, currentChannel, signature)) { result.error = null; result.method = currentMethod; result.result = address; indieCoreCallback(result); } else { result.error = new IndieCoreError("address not verified"); result.method = currentMethod; result.result = null; indieCoreCallback(result); } } else if (currentMethod == "signTransaction") { JsonData data = JsonMapper.ToObject(res); JsonData data1 = data ["data"]; string signedTx = data1 ["signed_tx"].ToString(); result.error = null; result.method = currentMethod; result.result = signedTx; indieCoreCallback(result); } else if (currentMethod == "getTokenDescriptionPart1") { JsonData data = JsonMapper.ToObject(res); string description = data["description"].ToString(); System.Uri uriResult; bool isURL = System.Uri.TryCreate(description, System.UriKind.Absolute, out uriResult) && (uriResult.Scheme == System.Uri.UriSchemeHttp || uriResult.Scheme == System.Uri.UriSchemeHttps); if (isURL) { currentMethod = "getTokenDescriptionPart2"; StartCoroutine(getAsync(description, HandleHttpAsyncCallback)); } else { result.error = null; result.method = currentMethod; result.result = description; indieCoreCallback(result); } } else if (currentMethod == "getTokenDescriptionPart2") { result.error = null; result.method = currentMethod; result.result = res; indieCoreCallback(result); } else { result.error = null; result.method = currentMethod; result.result = res; indieCoreCallback(result); } }
public void Prase_JSON() { //1.发送json并获取返回的json Kd_Send(); //try //{ // FileStream fs = new FileStream(@"C:\Users\sunkb.CHENZHU\Desktop\Receive_JSON.txt", FileMode.Open);//初始化文件流 // byte[] array = new byte[fs.Length];//初始化字节数组 // fs.Read(array, 0, array.Length);//读取流中数据到字节数组中 // fs.Close();//关闭流 // result = Encoding.UTF8.GetString(array);//将字节数组转化为字符串 //} //catch (Exception ex) //{ // MessageBox.Show("Error:" + ex.Message, "Error"); //} string jsonal = @"{""send"":" + param + ","; jsonal += @"""recive"":" + result + "}"; //2.解析返回结果的JSON JsonData jd = JsonMapper.ToObject(result); br.result = (bool)jd["result"]; br.message = (string)jd["message"]; br.status = (string)jd["status"]; JsonData jdItems = jd["data"]; if (br.status == "200" && br.result == true) { for (int i = 0; i < jdItems.Count; i++) { br.kuaidinum = (string)jdItems[i]["kuaidinum"]; if (result.Contains("returnNum")) { br.returnNum = (string)jdItems[i]["returnNum"]; } else { br.returnNum = ""; } if (result.Contains("childNum")) { br.childNum = (string)jdItems[i]["childNum"]; } else { br.childNum = ""; } if (result.Contains("bulkpen")) { br.bulkpen = (string)jdItems[i]["bulkpen"]; } else { br.bulkpen = ""; } if (result.Contains("orgCode")) { br.orgCode = (string)jdItems[i]["orgCode"]; } else { br.orgCode = ""; } if (result.Contains("orgName")) { br.orgName = (string)jdItems[i]["orgName"]; } else { br.orgName = ""; } if (result.Contains("destCode")) { br.destCode = (string)jdItems[i]["destCode"]; } else { br.destCode = ""; } if (result.Contains("destName")) { br.destName = (string)jdItems[i]["destName"]; } else { br.destName = ""; } if (result.Contains("orgSortingCode")) { br.orgSortingCode = (string)jdItems[i]["orgSortingCode"]; } else { br.orgSortingCode = ""; } if (result.Contains("orgSortingName")) { br.orgSortingName = (string)jdItems[i]["orgSortingName"]; } else { br.orgSortingName = ""; } if (result.Contains("destSortingCode")) { br.destSortingCode = (string)jdItems[i]["destSortingCode"]; } else { br.destSortingCode = ""; } if (result.Contains("destSortingName")) { br.destSortingName = (string)jdItems[i]["destSortingName"]; } else { br.destSortingName = ""; } if (result.Contains("orgExtra")) { br.orgExtra = (string)jdItems[i]["orgExtra"]; } else { br.orgExtra = ""; } if (result.Contains("destExtra")) { br.destExtra = (string)jdItems[i]["destExtra"]; } else { br.destExtra = ""; } if (result.Contains("pkgCode")) { br.pkgCode = (string)jdItems[i]["pkgCode"]; } else { br.pkgCode = ""; } if (result.Contains("pkgName")) { br.pkgName = (string)jdItems[i]["pkgName"]; } else { br.pkgName = ""; } if (result.Contains("road")) { br.road = (string)jdItems[i]["road"]; } else { br.road = ""; } if (result.Contains("qrCode")) { br.qrCode = (string)jdItems[i]["qrCode"]; } else { br.qrCode = ""; } if (result.Contains("orderNum")) { br.orderNum = (string)jdItems[i]["orderNum"]; } else { br.orderNum = ""; } if (result.Contains("expressCode")) { br.expressCode = (string)jdItems[i]["expressCode"]; } else { br.expressCode = ""; } if (result.Contains("expressName")) { br.expressName = (string)jdItems[i]["expressName"]; } else { br.expressName = ""; } br.templateurl = (string)jdItems[i]["templateurl"][0]; br.template = (string)jdItems[i]["template"][0]; } MessageBox.Show("提交成功!快递单号为:" + br.kuaidinum + ",请前往前台打印!", "发送成功!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Save_log(KdService.kdcompany + "发送正常!单号:" + br.kuaidinum, "", jsonal); } else { MessageBox.Show("快递单号获取失败,请重新输入!", "发送失败!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Save_log("发送数据格式错误!错误代码为:" + br.message, "", jsonal); } guid = System.Guid.NewGuid().ToString(); //写入表KD_detail string sqlsend = @"insert into KD_detail (ID,PrintDate,cancle,issend,rec_name,rec_mobil,rec_tel,rec_printaddr,rec_company,send_name,send_mobil,send_tel,send_printaddr,send_company,exptype,remark,needchild,neeBack,needtemplate,createuser,department,kdcompany) values(" + "'" + guid + "','" + DateTime.Now + "','0','0'," + "'" + Rec_name + "','" + Rec_mobile + "','" + Rec_tel + "','" + Rec_paddr + "','" + Rec_company + "','" + Send_name + "','" + Send_mobile + "','" + Send_tel + "','" + Send_paddr + "','" + Send_company + "'," + "'标准快递','" + Send_remark + "'" + ",'0','0','1','" + loginfo.userName + "','" + loginfo.userDepartMent + "','" + KdService.kdcompany + "'" + ")"; KdSql.Save_Sql(sqlsend); //写入数据库,表KD_detailentry string sqlre = @"insert into KD_detailentry (Finterid,kuaidinum,bulkpen,orgcode,orgname,destcode,destname,orgsortingcode,orgsortingname,destsortingcode,destsortingname,orgextra,destextra,pkgcode,road,qrcode,orderNum,expresscode,expressname,templater,url,pkgname,jsonval) values(" + "'" + guid + "','" + br.kuaidinum + "','" + br.bulkpen + "','" + br.orgCode + "','" + br.orgName + "','" + br.destCode + "','" + br.destName + "','" + br.orgSortingCode + "','" + br.orgSortingName + "','" + br.destSortingCode + "','" + br.destSortingName + "','" + br.orgExtra + "','" + br.destExtra + "','" + br.pkgCode + "','" + br.road + "','" + br.qrCode + "','" + br.orderNum + "','" + br.expressCode + "','" + br.expressName + "','" + br.template + "','" + br.templateurl + "','" + br.pkgName + "','" + jsonal + "'" + ")"; KdSql.Save_Sql(sqlre); //Print_Labels(); }
//public string GetPhoto() //{ // try // { // string code = CreateVerifyCode(); // Bitmap photo = CreateImageCode(code); // byte[] b_photo = null; // MemoryStream stream = new MemoryStream(); // using (photo) // { // photo.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); // } // photo.Dispose(); // using (stream) // { // b_photo = stream.GetBuffer(); // } // //stream.Dispose(); // stream.Close(); // string PhotoUrl = Convert.ToBase64String(b_photo, 0, b_photo.Length); // return PhotoUrl; // } // catch (Exception ex) // { // return ex.ToString(); // } //} //public void write() //{ // string PhotoUrl = GetPhoto(); // byte[] b = Convert.FromBase64String(PhotoUrl); // FileStream fs = new FileStream(@"F:/QQ文件/IMG_14.JPG",FileMode.Create,FileAccess.Write); // fs.Write(b,0,b.Length); // fs.Flush(); // fs.Close(); //} //核心企业提交入驻申请 #region public ResultCompEnter SendEnterRequest(string JSon, string version) { string PhoneNumb = string.Empty; string LoginName = string.Empty; string PassWord = string.Empty; string CompanyName = string.Empty; string Captcha = string.Empty; string SendId = string.Empty; string Type = string.Empty; int compid = 0; try { #region//JSon取值 JsonData JInfo = JsonMapper.ToObject(JSon); if (JInfo.Count > 0 && JInfo["PhoneNumb"].ToString().Trim() != "" && JInfo["LoginName"].ToString().Trim() != "" && JInfo["Captcha"].ToString().Trim() != "" && JInfo["PassWord"].ToString().Trim() != "" && JInfo["CompanyName"].ToString().Trim() != "" && JInfo["SendId"].ToString().Trim() != "" && JInfo["Type"].ToString().Trim() != "") { PhoneNumb = Common.NoHTML(JInfo["PhoneNumb"].ToString()); LoginName = Common.NoHTML(JInfo["LoginName"].ToString()); if (LoginName != JInfo["LoginName"].ToString()) { return new ResultCompEnter() { Result = "F", Description = "用户名存在非法字符串" } } ; PassWord = JInfo["PassWord"].ToString(); CompanyName = Common.NoHTML(JInfo["CompanyName"].ToString()); Captcha = JInfo["Captcha"].ToString(); SendId = JInfo["SendId"].ToString(); Type = JInfo["Type"].ToString(); } else { return(new ResultCompEnter() { Result = "F", Description = "参数异常" }); } #endregion #region//验证验证码是否有效 Hi.Model.SYS_PhoneCode code = new Hi.BLL.SYS_PhoneCode().GetModel(int.Parse(SendId)); if (code != null && code.dr == 0) { if (code.ts.AddMinutes(30) < DateTime.Now || code.IsPast == 1) { return new ResultCompEnter() { Result = "F", Description = "验证码过期" } } ; if (code.PhoneCode != Captcha) { return new ResultCompEnter() { Result = "F", Description = "验证码错误" } } ; } else { return(new ResultCompEnter() { Result = "F", Description = "验证码不可用" }); } code.IsPast = 1; code.ts = DateTime.Now; code.modifyuser = 0; SqlConnection conn = new SqlConnection(SqlHelper.LocalSqlServer); if (conn.State.ToString().ToLower() != "open") { conn.Open(); } SqlTransaction mytran = conn.BeginTransaction(); #endregion //如果验证码正确的话,修改验证码状态 try { if (new Hi.BLL.SYS_PhoneCode().Update(code, mytran))//验证码状态修改成功的话,开始进行注册流程 { if (Type == "distributor") { Boolean result = RegisterDistributor(CompanyName, PhoneNumb, PassWord, mytran); if (result) { return(new ResultCompEnter() { Result = "T", Description = "注册成功" }); } else { return(new ResultCompEnter() { Result = "F", Description = "注册用户失败" }); } } else { //首先在bd_company表中新增一条数据 Hi.Model.BD_Company comp = new Hi.Model.BD_Company(); comp.CompName = CompanyName; comp.LegalTel = PhoneNumb; comp.Phone = PhoneNumb; comp.AuditState = 0; comp.IsEnabled = 1; comp.FirstShow = 1; comp.Erptype = 0; comp.SortIndex = "001"; comp.HotShow = 1; comp.CreateDate = DateTime.Now; comp.CreateUserID = 0; comp.ts = DateTime.Now; comp.modifyuser = 0; compid = new Hi.BLL.BD_Company().Add(comp, mytran); //bd_company表中数据新增成功后,在sys_users表中新增一条数据 if (compid <= 0) { mytran.Rollback(); conn.Close(); return(new ResultCompEnter() { Result = "F", Description = "注册核心企业失败" }); } //在表sys_users表中新增一条数据 Hi.Model.SYS_Users user = new Hi.Model.SYS_Users(); user.UserName = LoginName; user.TrueName = ""; user.UserPwd = new GetPhoneCode().md5(PassWord); user.Phone = PhoneNumb; user.CreateDate = DateTime.Now; user.CreateUserID = 0; user.ts = DateTime.Now; user.modifyuser = 0; user.AuditState = 2; user.IsEnabled = 1; int userid = new Hi.BLL.SYS_Users().Add(user, mytran); if (userid <= 0) { mytran.Rollback(); conn.Close(); return(new ResultCompEnter() { Result = "F", Description = "注册用户失败" }); } //sys_users新增成功的话,在sys_compuser表中新增一条数据 Hi.Model.SYS_CompUser compuser = new Hi.Model.SYS_CompUser(); compuser.CompID = compid; compuser.DisID = 0; compuser.CreateDate = DateTime.Now; compuser.CreateUserID = 0; compuser.ts = DateTime.Now; compuser.modifyuser = 0; compuser.CType = 1; compuser.UType = 4; compuser.dr = 0; compuser.IsAudit = 0; compuser.IsEnabled = 1; compuser.UserID = userid; int compuserid = new Hi.BLL.SYS_CompUser().Add(compuser, mytran); if (compuserid <= 0) { mytran.Rollback(); conn.Close(); return(new ResultCompEnter() { Result = "F", Description = "用户与核心企业关联失败" }); } else { // 通知运营 string SendRegiPhone = System.Configuration.ConfigurationManager.AppSettings["SendTels"].ToString(); string[] Phones = SendRegiPhone.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string tel in Phones) { GetPhoneCode phoneCode = new GetPhoneCode(); phoneCode.GetUser( System.Configuration.ConfigurationManager.AppSettings["PhoneCodeAccount"].ToString(), System.Configuration.ConfigurationManager.AppSettings["PhoneCodePwd"].ToString()); phoneCode.ReturnComp(tel, comp.CompName); } } } } else { mytran.Rollback(); conn.Close(); return(new ResultCompEnter() { Result = "F", Description = "验证码异常" }); } } catch { mytran.Rollback(); conn.Close(); } mytran.Commit(); conn.Close(); return(new ResultCompEnter() { Result = "T", Description = "注册成功", CompID = compid.ToString() }); } catch (Exception ex) { Common.CatchInfo(ex.Message + ":" + ex.StackTrace, "SendEnterRequest" + JSon); return(new ResultCompEnter() { Result = "F", Description = "参数异常" }); } }
/// <summary> /// 根据object生成string /// </summary> /// <param name="value"></param> /// <returns></returns> public static string SerializeObject(object value) { string result = JsonMapper.ToJson(value); return(result); }
public static object FromJson(Type type, byte[] bytes, int index, int count) { string str = bytes.ToStr(index, count); return(JsonMapper.ToObject(type, str)); }
/// <summary> /// 根据string解析成object<T> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public static T DeserializeObject <T>(string value) { T result = JsonMapper.ToObject <T>(value); return(result); }
public static T FromJson <T>(byte[] bytes, int index, int count) { string str = bytes.ToStr(); return(JsonMapper.ToObject <T>(str)); }
public static void LoadHotfix(string dllPath, bool isRegisterBindings = true) { // IsRunning = true; string pdbPath = dllPath + ".pdb"; BDebug.Log("DLL加载路径:" + dllPath, "red"); // AppDomain = new AppDomain(); if (File.Exists(pdbPath)) { //这里的流不能释放,头铁的老哥别试了 fsDll = new FileStream(dllPath, FileMode.Open, FileAccess.Read); fsPdb = new FileStream(pdbPath, FileMode.Open, FileAccess.Read); AppDomain.LoadAssembly(fsDll, fsPdb, new PdbReaderProvider()); } else { //这里的流不能释放,头铁的老哥别试了 fsDll = new FileStream(dllPath, FileMode.Open, FileAccess.Read); AppDomain.LoadAssembly(fsDll); } #if UNITY_EDITOR AppDomain.UnityMainThreadID = System.Threading.Thread.CurrentThread.ManagedThreadId; #endif //绑定的初始化 //ada绑定 AdapterRegister.RegisterCrossBindingAdaptor(AppDomain); //delegate绑定 ILRuntimeDelegateHelper.Register(AppDomain); //值类型绑定 AppDomain.RegisterValueTypeBinder(typeof(Vector2), new Vector2Binder()); AppDomain.RegisterValueTypeBinder(typeof(Vector3), new Vector3Binder()); AppDomain.RegisterValueTypeBinder(typeof(Vector4), new Vector4Binder()); AppDomain.RegisterValueTypeBinder(typeof(Quaternion), new QuaternionBinder()); //是否注册各种binding if (isRegisterBindings) { CLRBindings.Initialize(AppDomain); CLRManualBindings.Initialize(AppDomain); // ILRuntime.Runtime.Generated.PreCLRBuilding.Initialize(AppDomain); } JsonMapper.RegisterILRuntimeCLRRedirection(AppDomain); if (BDLauncher.Inst != null && BDLauncher.Inst.Config.IsDebuggerILRuntime) { AppDomain.DebugService.StartDebugService(56000); Debug.Log("热更调试器 准备待命~"); } // AppDomain.Invoke("HotfixCheck", "Log", null, null); }
public static JsonData httpWebRequestPostFile(string url, List<FormItem> itemList, OnHttpWebRequestCallback callback, object callbakcUserData, bool logError) { // 以模拟表单的形式上传数据 string boundary = "----" + DateTime.Now.Ticks.ToString("x"); string fileFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + "\r\nContent-Type: application/octet-stream" + "\r\n\r\n"; string dataFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}"; MemoryStream postStream = new MemoryStream(); foreach (var item in itemList) { string formdata = null; if (item.mFileContent != null) { formdata = string.Format(fileFormdataTemplate, "fileContent", item.mFileName); } else { formdata = string.Format(dataFormdataTemplate, item.mKey, item.mValue); } // 统一处理 byte[] formdataBytes = null; // 第一行不需要换行 if (postStream.Length == 0) { formdataBytes = stringToBytes(formdata.Substring(2, formdata.Length - 2), Encoding.UTF8); } else { formdataBytes = stringToBytes(formdata, Encoding.UTF8); } postStream.Write(formdataBytes, 0, formdataBytes.Length); // 写入文件内容 if (item.mFileContent != null && item.mFileContent.Length > 0) { postStream.Write(item.mFileContent, 0, item.mFileContent.Length); } } // 结尾 byte[] footer = stringToBytes("\r\n--" + boundary + "--\r\n", Encoding.UTF8); postStream.Write(footer, 0, footer.Length); byte[] postBytes = postStream.ToArray(); ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); webRequest.Method = "POST"; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; webRequest.Timeout = 10000; webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.ContentLength = postBytes.Length; // 异步 if (callback != null) { RequestThreadParam threadParam = new RequestThreadParam(); threadParam.mRequest = webRequest; threadParam.mByteArray = postBytes; threadParam.mCallback = callback; threadParam.mUserData = callbakcUserData; threadParam.mFullURL = url; threadParam.mLogError = logError; Thread httpThread = new Thread(waitPostHttpWebRequest); threadParam.mThread = httpThread; httpThread.Start(threadParam); httpThread.IsBackground = true; ThreadListLock.waitForUnlock(); mHttpThreadList.Add(httpThread); ThreadListLock.unlock(); return null; } // 同步 else { try { // 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。) // 创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面 Stream newStream = webRequest.GetRequestStream(); newStream.Write(postBytes, 0, postBytes.Length); newStream.Close(); // 读取服务器的返回信息 HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string phpend = php.ReadToEnd(); php.Close(); response.Close(); return JsonMapper.ToObject(phpend); } catch (Exception) { return null; } } }
/// <summary> /// 将 JSON 字符串反序列化为对象。 /// </summary> /// <typeparam name="T">对象类型。</typeparam> /// <param name="json">要反序列化的 JSON 字符串。</param> /// <returns>反序列化后的对象。</returns> public T ToObject <T>(string json) { return(JsonMapper.ToObject <T>(json)); }
public void Awake() { foreach (SavedObjType type in Enum.GetValues(typeof(SavedObjType))) { savedObjLists[type] = new List <ObjectInfo>(); } if (File.Exists(Application.dataPath + EnvironmentSaver.EnviromentDataPath)) { savedObjLists[SavedObjType.EnvironmentObjects] = JsonMapper.ToObject <List <ObjectInfo> >(File.ReadAllText(Application.dataPath + EnvironmentSaver.EnviromentDataPath)); } if (File.Exists(Application.dataPath + EnvironmentSaver.TileDataPath)) { savedObjLists[SavedObjType.Tiles] = JsonMapper.ToObject <List <ObjectInfo> >(File.ReadAllText(Application.dataPath + EnvironmentSaver.TileDataPath)); } if (File.Exists(Application.dataPath + EnvironmentSaver.NPCsDataPath)) { savedObjLists[SavedObjType.NPCs] = JsonMapper.ToObject <List <ObjectInfo> >(File.ReadAllText(Application.dataPath + EnvironmentSaver.NPCsDataPath)); } if (File.Exists(Application.dataPath + EnvironmentSaver.InitInventoryDataPath)) { savedObjLists[SavedObjType.Inventory] = JsonMapper.ToObject <List <ObjectInfo> >(File.ReadAllText(Application.dataPath + EnvironmentSaver.InitInventoryDataPath)); } // Player info if (File.Exists(Application.dataPath + SaveManager.PlayerDataPath)) { savedPlayer = JsonMapper.ToObject <CharacterInfo>(File.ReadAllText(Application.dataPath + SaveManager.PlayerDataPath)); LoadPlayerInfo(); } // Quests if (File.Exists(Application.dataPath + SaveManager.QuestDataPath)) { List <Quest> QuestData = JsonMapper.ToObject <List <Quest> >(File.ReadAllText(Application.dataPath + SaveManager.QuestDataPath)); if (QuestData != null) { QuestManager.ListOfQuests = QuestData; } Quest q = QuestManager.GetQuestByID("ThorinIntroQuest"); if (q.ID != null) { GameManager.InTutorial = !q.Completed; } } // Dialogue Variables if (File.Exists(Application.dataPath + SaveManager.DialogueDataPath)) { DialogueSaver dialogueSaver = JsonMapper.ToObject <DialogueSaver>(File.ReadAllText(Application.dataPath + SaveManager.DialogueDataPath)); if (dialogueSaver != null) { dialogueSaver.LoadToDialogBox(); } } // Unlocked Spells // if (File.Exists(Application.dataPath + SpellManager.InitializedUnlockedSpellsPath) && !File.Exists(Application.dataPath + SpellManager.UnlockedSpellsPath)) // { // JsonData spellsData = JsonMapper.ToJson(JsonMapper.ToObject(File.ReadAllText(Application.dataPath + SpellManager.InitializedUnlockedSpellsPath))); // File.WriteAllText(Application.dataPath + SpellManager.UnlockedSpellsPath, spellsData.ToString()); // } if (ChunkManager.TileReference == null) { ChunkManager.TileReference = new Dictionary <string, TileBase>(); // string[] allFiles = Directory.GetFiles("Assets/Resources/Tiles/WorldTiles"); Dictionary <string, string> tileFileNames = new Dictionary <string, string>(); if (Application.isEditor) { string[] allFiles = Directory.GetFiles(Application.dataPath + "/Resources/Tiles/WorldTiles"); for (int i = 0; i < allFiles.Length; i++) { if (allFiles[i].Contains(".meta")) { continue; } string prefabName = Path.GetFileNameWithoutExtension(allFiles[i]); // Help.print(prefabName); string tileFile = "Tiles/WorldTiles/" + prefabName; tileFileNames.Add(tileFile, prefabName); } // Save the tileFileNames JsonData tileFileNameData = JsonMapper.ToJson(tileFileNames); File.WriteAllText(Application.dataPath + TileFileNameJsonPath, tileFileNameData.ToString()); } else { // Read from json if (File.Exists(Application.dataPath + TileFileNameJsonPath)) { tileFileNames = JsonMapper.ToObject <Dictionary <string, string> >(File.ReadAllText(Application.dataPath + TileFileNameJsonPath)); } else { throw new FileNotFoundException("Streaming Assets " + TileFileNameJsonPath + " Path not found."); } } foreach (KeyValuePair <string, string> tileFileName in tileFileNames) { TileBase tile = Resources.Load <TileBase>(tileFileName.Key); ChunkManager.TileReference.Add(tileFileName.Value, tile); } } SpellManager.LoadSpells(); }
public static T GetJsonObj <T>(string json) { return(JsonMapper.ToObject <T>(json)); }
public JsonAnalysis(string message) { jd = JsonMapper.ToObject(message); }
public void LoadLocalization() { string jsonstring = File.ReadAllText(Application.dataPath + "/StreamingAssets" + "/Localization.json"); LocalizationData = JsonMapper.ToObject(jsonstring); }