This is my response ... My dictnary name is "msg"
{
Result = {
Data = {
engine = {
service = {
data = (
{
checked = 1;
field = 1;
name = Ettersyn;
},
{
checked = 1;
field = 1;
name = "Med Alpha VP";
},
{
checked = 0;
field = 0;
name = "Med B.IMP.";
}
);
"engine_service_id" = 1;
"engine_service_name" = "4 Cyl";
};
type = {
"engine_id" = 1;
"engine_name" = Benzin;
};
};
tact = {
service = {
data = (
{
checked = 0;
field = 1;
name = "Little ettersyn";
},
{
checked = 0;
field = 1;
name = "Short ettersyn";
}
);
"tact_service_id" = 2;
"tact_service_name" = "21-50 hk";
};
type = {
"tact_id" = 1;
"tact_name" = "2 Takt";
};
};
};
status = success;
};
}
I try to to store the data like this
var arrayMain : NSMutableArray = msg.valueForKey("Result")?.valueForKey("Data") as NSMutableArray
My problem is i got "EXC_BAD_ACCESS" error While running ... Am also check allocation of array ... I try to store it in NSMutableDictionary its work perfectly ... How can i store this response in NSMutableArray ?
If you look carefully at the response data structure you'll see the problem.
This first operation: msg.valueForKey("Result") would return an dictionary with two key/values; a "Data" dictionary, and "Status" string.
Your second operation .valueForKey("Data") would return a dictionary with two key/values; an "Engine and "Tact" dictionary.
Because it's a dictionary, you can create a dictionary from it, which is what you said worked, or you're going to have to rethink how you want to store if if indeed you want it in an array, but you can't create an array directly from a dictionary - they are different data structures.
You cannot assign Dictionary object to Array, that's why it is giving the error.
But you can store that dictionary to array as:
var arrayMain : NSMutableArray = NSMutableArray()
arrayMain.addObject(msg.valueForKey("Result")?.valueForKey("Data"))
Related
My C# MVC5 Razor page returns a Newtonsoft json link object to my controller (the "1" before \nEdit |" indicates that the checkbox is checked:
"{\"0\": [\"6146\",\"Kimball\",\"Jimmy\",\"General Funny Guy\",\"277\",\"Unite\",\"Jun 2019\",\"\",\"\",\"1\",\"\nEdit |\nDetails\n\n \n\"],\"1\": [\"6147\",\"Hawk\",\"Jack\",\"\",\"547\",\"Painters\",\"Jun 2019\",\"\",\"\",\"on\",\"\nEdit |\nDetails\n\n \n\"]}"
How do I parse this?
I am using a WebGrid to view and I want to allow the users to update only the lines they want (by checking the checkbox for that row), but it doesn't include an id for the 's in the dom. I figured out how to pull the values, but not the fieldname: "Last Name" , value: "Smith"... I only have the value and can't seem to parse it... one of my many failed attempts:
public ActoinResult AttMods(string gridData)
{
dynamic parsedArray = JsonConvert.DeserializeObject(gridData);
foreach (var item in parsedArray)
{
string[] itemvalue = item.Split(delimiterChars);
{
var id = itemvalue[0];
}
}
I finally sorted this one out..If there is a more dynamic answer, please share... I'll give it a few days before I accept my own (admittedly clugy) answer.
if(ModelState.IsValid)
{
try
{
Dictionary <string,string[]> log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
foreach (KeyValuePair<string,string[]> keyValue in log)
{
if (keyValue.Value[9] == "1")//Update this row based on the checkbox being checked
{
var AttendeeID = keyValue.Value[0];
int intAttendeeID = 0;
if (int.TryParse(AttendeeID, out intAttendeeID))//Make sure the AttendeeID is valid
{
var LName = keyValue.Value[1];
var FName = keyValue.Value[2];
var Title = keyValue.Value[3];
var kOrgID = keyValue.Value[4];
var Org = keyValue.Value[5];
var City = keyValue.Value[7];
var State = keyValue.Value[8];
var LegalApproval = keyValue.Value[9];
tblAttendee att = db.tblAttendees.Find(Convert.ToInt32(AttendeeID));
att.FName = FName;
att.LName = LName;
att.Title = Title;
att.kOrgID = Convert.ToInt32(kOrgID);
att.Organization = Org;
att.City = City;
att.State = State;
att.LegalApprovedAtt = Convert.ToBoolean(LegalApproval);
}
}
}
db.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
You can avoid assigning the var's and just populate the att object with the KeyValue.Value[n] value, but you get the idea.
I am developing a ASP.NET MVC Web Api. Project. I am returning data with JSON format. Before I return data to user I serialize data using JsonConvert.SerializeObject to change their json property names.My code return data in JSON format. But with an issue. That is it always return data into string even if the data is array or object.
This is my action method that returns json.
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions!=null && dbRegions.Count()>0)
{
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
if(!string.IsNullOrEmpty(json))
{
json = json.Trim(new char[] { '"' });
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent(json.GetType(),json,Configuration.Formatters.JsonFormatter)
};
}
Actually this code should return Json array. But when I parse data from client (from Android using Volley). It cannot be parsed into Json Array.
This is the data I get:
As you can see the double quote both in the beginning and at the end. The reason I cannot parse it into array in Volley is it is returning as a string because of that double. How can I serialize it trimming that quote? I used trim, but not removed.
You are unnecessarily complicating things. In Web API you can return JSON just by returning any object inside the built-in methods, the framework will serialize it for you.
public IHttpActionResult Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions != null && dbRegions.Count() > 0) {
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
return Ok(regions);
}
As an aside: from what I can see you are mapping manually your domain objects into DTOs: take into consideration the use of an automatic mapping mechanism like AutoMapper.
I am not sure this is the best solution or not. I solved the problem using this way.
This is my action method
public HttpResponseMessage Get()
{
try
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.Default, "application/json")
};
}
catch
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
It's not required to convert object to json string.
You can try :
return Request.CreateResponse<List<ContentRegion>>(HttpStatusCode.OK,regions);
Not tested.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Use this line in your WebApiConfig.
And here your code should be
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
HttpResponseMessage temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "");
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, regions);
return temp;
//string json = JsonConvert.SerializeObject(regions);
//if (!string.IsNullOrEmpty(json))
//{
// json = json.Trim(new char[] { '"' });
//}
//return new HttpResponseMessage(HttpStatusCode.OK)
//{
// Content = new ObjectContent(json.GetType(), json, Configuration.Formatters.JsonFormatter)
//};
}
iv'e been trying for few days to get parameters from specific json structure with no success so far. I have a NSDictionary that get json data (i need the mToken and data from mHeader for example)
{
"$id" = 1;
mHeaders = (
{
"$id" = 4;
mPoints = 0;
mRealLeagueId = 57172a6e2276fe28bcf0d91c;
mTeamId = 57172a762276fe28bcf0e053;
mTeamLogo = avatar;
mTeamName = "Hungry Animals";
}
);
mToken = "5k8ziTBn0G5Gozs7qz68LCLBfLSgymOcLwRshMax1Q5pZi4bx6hbEOFgupoXrBNNGzsWosLs6KPsK6cG1kk/9o5778Y7JEKfo3CAPXS7qAg=";
mUser = {
"$id" = 2;
mAge = 42;
mCreateDate = "2016-04-20T07:06:30.507Z";
mEmail = "email0#gmail.com";
mFirstName = Alesandro;
mGender = 1;
mId = 57172a762276fe28bcf0e06d;
mLastLogin = "2016-04-21T07:20:40.402Z";
mLastName = Zohar;
mLogo = avatar;
mNick = "Big Boss 0";
mRegion = Global;
mTeams = (
{
"$id" = 3;
mRealLeagueId = 57172a6e2276fe28bcf0d91c;
mTeamId = 57172a762276fe28bcf0e053;
}
);
mTokens = 9644998;
};
}
So you have a dictionary after parsing the json. You need mToken which in root level of the json data, you can simply get the value by
jsonDict["mToken"]
Your mHeader is an array of dictionary so for getting the value, Do like this
for dict in jsonDict["mHeaders"] as! Array<NSDictionary> {
print(dict["mRealLeagueId"]) //prints 57172a6e2276fe28bcf0d91c
print(dict["mTeamId"]) //57172a762276fe28bcf0e053
}
Hope this helps
I am having following structure currently present in my database, i am executing a service to fetch data from REST api and storing it to my database , so that i can use it to display it frequently on UI as like caching a data
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 53,
"activeProjectCount" : 29,
"completedProjectCount" : 1,
"userCount" : 85
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 48,
"activeProjectCount" : 41,
"completedProjectCount" : 0,
"userCount" : 123
}
My collection is going to remain same only values will be going to change, so please suggest me a way in which i can place the updated values in mongo and at the same time i can fetch data on my UI
my new values might be like
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 23,
"activeProjectCount" : 17,
"completedProjectCount" : 1,
"userCount" : 60
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 45,
"activeProjectCount" : 40,
"completedProjectCount" : 0,
"userCount" : 113
}
function to fetch data from REST api
def getCount(String companyName, String apiKey) {
//declaration section
List returnList = []
int totalProjectCount = 0 //variable to hold total no of projects value
int activeProjectCount = 0 //variable to hold total active projects value
int completedProjectCount = 0 //variable to hold total completed projects value
int userCount = 0 //variable to hold total active user count
String userAPIKey = apiKey //user API key for authorization
String method = 'GET' //method of request
String totalProjectURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ALL" // Url to access All projects
StringBuilder out = getConnection(totalProjectURL, method, userAPIKey) //String builder to hold result
//catching result into json
JSONObject object = new JSONObject(out.toString()) //JSON object to store String in json format
totalProjectCount = object.projects.length()
String activeProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ACTIVE" // Url to access Active projects
out = getConnection(activeProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
activeProjectCount = object.projects.length()
String completedProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=COMPLETED" // Url to access completed projects
out = getConnection(completedProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
completedProjectCount = object.projects.length()
String peopleURL = "https://"+ companyName + ".teamwork.com/people.json" // Url to access total active users
out = getConnection(peopleURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
userCount = object.people.length()
Map returnMap = [:]
returnMap.put('totalProjectCount', totalProjectCount)
returnMap.put('activeProjectCount', activeProjectCount)
returnMap.put('completedProjectCount', completedProjectCount)
returnMap.put('userCount', userCount)
addCount(returnMap, 'curo', 'countDetails')
println('project count successfully saved.')
}
function to add countDetails to mongo
def addCount(Map userMap, String dbName, String collectionName) {
try {
DB db = mongo.getDB(dbName)
DBCollection table = db.getCollection(collectionName)
table.insert(userMap as BasicDBObject)
def srvcResponseObj = [ responseStatus : "pass", responseCode : 200 ]
return srvcResponseObj
}
catch (Exception e)
{
println "Exception related to Mongo add record"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
function to fetch data from mongo
def fetchCountDetails(String databaseName, String collectionName) {
println 'inside fetch count details'
try {
DB db = mongo.getDB(databaseName)
DBCollection table = db.getCollection(collectionName)
DBCursor cursor = table.find()
Map returnCountMap = [:]
List temp = []
int cursorCounter = 0
while(cursor.hasNext()) {
Map temporaryMap = [:]
BasicDBObject doc = (BasicDBObject) cursor.next()
doc.remove('_id')
temp.add(doc)
cursorCounter++
}
returnCountMap.put('totalProjectCount', temp.totalProjectCount.sum())
returnCountMap.put('activeProjectCount',temp.activeProjectCount.sum())
returnCountMap.put('completedProjectCount',temp.completedProjectCount.sum())
returnCountMap.put('userCount',temp.userCount.sum())
if(cursorCounter>1)
println "Multiple objects found for eventID"
if(cursorCounter==0)
println "No objects found for eventID"
return returnCountMap
}
catch (Exception e)
{
println "Exception related to Mongo >> fetchUserDetails"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
now i am making request to REST api after fixed amount of interval and my response gets changed in terms of values, but if i call the add function again and again my documents get duplicated in mongodb and my expected result is that my new values gets reflected in mongodb
I am getting the following data in JSON format by the Facebook graph API. However it looks like it is in invalid JSON format. The JSON formatter says that the error is in line 1. What is this error ?
{
data = (
{
application = {
id = 2409997254;
name = Likes;
};
"created_time" = "2013-05-05T07:51:41+0000";
from = {
id = 100000347121257;
name = "Rishab Gulati";
};
id = "notif_746853089_182660043";
link = "http://www.facebook.com/photo.php?fbid=10151457234013090&set=a.427064503089.223857.746853089&type=1";
object = "<null>";
title = "Rishab Gulati, Deepika Gurnani and 2 other people like your photo.";
to = {
id = 746853089;
name = "Ashish Agarwal";
};
unread = 1;
"updated_time" = "2013-05-05T10:48:33+0000";
}
);
paging = {
next = "https://graph.facebook.com/746853089/notifications?format=json&access_token=**xxxxxxxxxx";
previous = "https://graph.facebook.com/746853089/notifications?format=json&access_token=**SNIP**&limit=5000&since=1367740301&__paging_token=notif_746853089_182660043&__previous=1";
};
summary = {
"unseen_count" = 1;
"updated_time" = "2013-05-05T10:48:33+0000";
};
}
This data is incorrect and isn't what Facebook supplies
{
"data": [
{
Where as your JSON above shows
{
data = (
{
There is a ( when there should be a {
Also consider not giving your access token out in public.