I have Json response through Facebook API like this:
Now I want to parse this data so I can use within my game. For this purpose, I have written code up to this:
public void OnChallengesButtonClick ()
{
SoundManager.Instance.PlayButtonClickSound ();
FB.API ("/me/friends", HttpMethod.GET, RetrieveFacebookFriends);
}
public void RetrieveFacebookFriends (IGraphResult result)
{
if (!string.IsNullOrEmpty (result.Error)) {
Debug.Log ("ERROR: " + result.Error);
return;
}
IDictionary<string,object> friendsDict = result.ResultDictionary;
Debug.Log ("raw: " + result.RawResult);
}
So how to extract name and ID data from available Json response through Dictionary object?
Basically you should create a class to serialize/deserialize an object:
class FBResponse
FBDataResponse data;
class FBDataResponse
string name;
string id;
Take a look to my response here for more details (after "Final EDIT" part):
Converting arrays of arrays to json
It should be easy to create those two class and use them to deserialize the FB response. Just remember that your variables will need to match the same name with the json response from Facebook (for example you cannot call data data1).
After you have the object it should be easy to do what you want with it... and with the object you should be able to get the json again.
PS. Unity default json serializer does not support Dictionary that's why you need to serialize two object. If you don't want that you should try to use a different library.
I think this is all I need: JSON with Unity
friends = (List<object>)(((Dictionary<string, object>)friendsH) ["data"]);
if(friends.Count > 0) {
var friendDict = ((Dictionary<string,object>)(friends[0]));
var friend = new Dictionary<string, string>();
friend["id"] = (string)friendDict["id"];
friend["first_name"] = (string)friendDict["first_name"];
}
Before I can't able to find this post from Facebook.
Related
Mostly this is about just sending hard coded JSON from Web API method back to a caller app ( happens to be React). My current action looks something like the following:
[Route("members/{memberId}")]
public async Task<IActionResult> Members(string memberId)
{
// {
// "SecA4": ["Asian"]
// }
// ?? string json = "{ \"SecA4\": [\"Asian\"] }"; //??
return OK() // need to place JSON in the OK() method. but how should it be done?
}
So currently I am able to load from a file into a survey engine a file that looks like that. Thus I load from a .json file.
{
"SecA4": ["Asian"]
}
Rather then a hard-coded string I would use an object rather, which would be done something like the following
object someObject = new
{
SecA4 = "Asian"
};
You can create this pretty much the same way as you would do with Json.
Now we are just returning the newly created object and converting it into Json.
return Json(someObject, new JsonSerializerSettings() { Formatting = Formatting.None });
Where in the JsonSerializerSettings you can tell Newtonsoft.Json to no use any formatting e.g. new lines, spaces and so on.
I try to create JSON format from Realm Results using Object Mapper. So, I created two generic methods to do that. Fisrt method create array form Results and looks like that:
var allRealmData: Results<Project>? // in this variable I save all Project Objects first
func makeAnArrayFromResults<T>(object: T.Type) -> [T]?{
var array = [T]()
guard let mainArray = allRealmData else { return nil }
for i in mainArray {
if let object = i as? T {
array.append(object)
}
}
return array
}
then I would like to use Object Mapper to change this array to JSON Object, but when I try do it, I receive an error and don't know how can I resolve it. My second method looks like that:
func createJSON<T: Object>(object: T.Type){
let array = makeAnArrayFromResults(object)
let json = Mapper().toJSONString(array!, prettyPrint: true) //here error
}
error info: Cannot invoke "toJSONString" with an argument list of type"([T], prettyPrint: Bool)".
Do you have any sugestions how can I create JSON from Result in Realm?
Firstly, makeAnArrayFromResults<T> is really just map:
let someRealmResults: Results<Project>?
...
let array = someRealmResults?.map { $0 } // => [Project]?
As far as the Object Mapper integration goes, it looks like you don't have a toJSONString function defined that satisfies the first argument type constraints of [Person].
There's quite a bit of discussion in Object Mapper's issue tracker about interoperability with Realm that you may find useful: https://github.com/Hearst-DD/ObjectMapper/issues/475
I'm trying to parse JSON data from URL and show the data in my app.
JSON Example (After accessing specific URL):
[{"placeID":"1","placeName":"Test Place","city":"New York","type":"Rest"..
How I can read this data and show a list of the places recieved from the API?
I've been trying ALL of the guides over the internet for parsing JSON data from URL with Android Studio and without. As a total beginner with Android developement, I couldn't make one working exmaple with json even when the author shared the final example for download. I hope you can help me in noob-friendly way and step by step or refer me to the right places.
Thank you!
I believe Android uses org.json as the JSON library, in which case something like this works to retrieve information about each place (assuming data is a valid JSON string)
try {
String data = "\"[{\"placeID\":\"1\",\"placeName\":\"Test Place\",\"city\":\"New York\",\"type\":\"Rest\"..";
JSONArray places = new JSONArray(data);
for (int i = 0; i < places.length(); i++)
JSONObject place = (JSONObject) places.get(i);
int id = place.getInt("id");
String name = place.getString("placeName");
String city = place.getString("city");
// etc...
// Do what you wish with the id, name, city and other variables.
// It loops through here for each item in the JSON variable.
}
} catch (JSONException e) {
e.printStackTrace();
}
This goes through each place in the JSON array and grabs some of the variables from it. It would probably be smart to create a data class and call it something like Place. You could then pass in the data with a constructor: new Place(id, name, city); (see this constructor for example: https://stackoverflow.com/a/22419370/5236779).
Please pardon me if this is a repeat question. I have been through some of the questions/answers with a similar requirement but somehow got a bit overwhelmed and confused at the same time. My requirement is:
I get a JSON string/object as a request parameter. ( eg: params.timesheetJSON )
I then have to parse/iterate through it.
Here is the JSON that my grails controller will be receiving:
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
Questions:
How can I retrieve the whole JSON string from the request? Does request.JSON be fine here? If so, will request.JSON.timesheetJSON yield me the actual JSON that I want as a JSONObject?
What is the best way to parse through the JSON object that I got from the request? Is it grails.converters.JSON? Or is there any other easy way of parsing through? Like some API which will return the JSON as a collection of objects by automatically taking care of parsing. Or is programatically parsing through the JSON object the only way?
Like I said, please pardon me if the question is sounding vague. Any good references JSON parsing with grails might also be helpful here.
Edit: There's a change in the way I get the JSON string now. I get the JSON string as a request paramter.
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def object1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now.
I have wrote some code that explains how this can be done, that you can see below, but to be clear, first the answers to your questions:
Your JSON String as you wrote above will be the contents of your POST payload to the rest controller. Grails will use its data binding mechanism to bind the incomming data to a Command object that your should prepare. It has to have fields corresponding to the parameters in your JSON String (see below). After you bind your command object to your actual domain object, you can get all the data you want, by simply operating on fields and lists
The way to parse thru the JSON object is shown in my example below. The incomming request is esentially a nested map, with can be simply accessed with a dot
Now some code that illustrates how to do it.
In your controller create a method that accepts "YourCommand" object as input parameter:
def yourRestServiceMethod (YourCommand comm){
YourClass yourClass = new YourClass()
comm.bindTo(yourClass)
// do something with yourClass
// println yourClass.timeSheetList
}
The command looks like this:
class YourCommand {
String loginName
List<Map> timesheetList = []
String overallStatus
void bindTo(YourClass yourClass){
yourClass.loginName=loginName
yourClass.overallStatus=overallStatus
timesheetList.each { sheet ->
TimeSheet timeSheet = new TimeSheet()
timeSheet.periodBegin = sheet.periodBegin
timeSheet.periodEnd = sheet.periodEnd
sheet.timesheetRows.each { row ->
TimeSheetRow timeSheetRow = new TimeSheetRow()
timeSheetRow.task = row.task
timeSheetRow.description = row.description
timeSheetRow.paycode = row.paycode
timeSheet.timesheetRows.add(timeSheetRow)
}
yourClass.timeSheetList.add(timeSheet)
}
}
}
Its "bindTo" method is the key piece of logic that understands how to get parameters from the incomming request and map it to a regular object. That object is of type "YourClass" and it looks like this:
class YourClass {
String loginName
Collection<TimeSheet> timeSheetList = []
String overallStatus
}
all other classes that are part of that class:
class TimeSheet {
String periodBegin
String periodEnd
Collection<TimeSheetRow> timesheetRows = []
}
and the last one:
class TimeSheetRow {
String task
String description
String paycode
}
Hope this example is clear enough for you and answers your question
Edit: Extending the answer according to the new requirements
Looking at your new code, I see that you probably did some typos when writting that post
def jsonArray = jsonArray.timesheetList
should be:
def jsonArray = jsonObject.timesheetList
but you obviously have it properly in your code since otherwise it would not work, then the same with that line with "println":
jsonArray1.size()
shuold be:
jsonArray.size()
and the essential fix:
def object1 = jsonArray[1]
shuold be
def object1 = jsonArray[0]
your array is of size==1, the indexing starts with 0. // Can it be that easy? ;)
Then "object1" is again a JSONObject, so you can access the fields with a "." or as a map, for example like this:
object1.get('periodEnd')
I see your example contains errors, which lead you to implement more complex JSON parsing solutions.
I rewrite your sample to the working version. (At least now for Grails 3.x)
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON)
println jsonObject.timesheetList // output timesheetList structure
println jsonObject.timesheetList[0].timesheetRows[1] // output second element of timesheetRows array: [paycode:payCode2, task:painting, activityDescription:painting description]
using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for