json parse returning null - json

i am trying to parse some json for the first time. My json looks like this:
{"categoryid":"2","accountid":"1","title":"Bed for sale","price":"2.99","description":"brand new bed ....}]
I've been trying to follow this tutorial:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
However, his JSON looks like:
{"paging":{"page":1,"total":123,"page_size":20,"pages":7},"loans":[{"id":519535,"name":"Oyunbat","description":{"languages": ....
The code in the tutorial expects the objectID "loans" however the JSON i'm attempting to parse does not have this objectID. It just has the value/key pairs.
My problem seems to be with this part of the code:
NSArray* latestLoans = [json objectForKey:#"title"];
Where the dictionary is placed into an array. But since i do not have this objectID in my JSON i am getting a null returned and no data.
How can i do just a simple parse of the JSON i have by putting into an array?
Thank you very much for any help! I'm new to this and trying to get going.

Looks like a root and child. Try this:
dict = [resp objectForKey:#"paging"];
if( ( dict == nil ) || ![dict isKindOfClass:[NSDictionary class]] ) {
NSLog( #"WARNING: %#", [dict description]);
return;
}
Title = [[dict objectForKey:#"title"]copy];
NSLog(#"Your Value: %#", Title);

Related

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));

convert jsonelement to json array in a json object from xml using org.json

I am using org.json to convert an xml to json using below code snippet.Unfotunately, there is a structure called "countries" which is supposed to be an array, but can have only 1 country sometimes. In such cases, array is not getting disaplyed instead "countries" is showing up under {} instead of [{}] or [].
JSONObject xmlJSONObj = XML.toJSONObject(xsltresponse);
return xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
output i am getting is with after json conversion is:
{
"data":{
"name":"Microsoft",
"date":"today",
"countries":{
"name:"AN"
}}}
Instead of getting below output
{
"data":{
"name":"Microsoft",
"date":"today",
"countries":[{
"name:"AN"
}]
}}
How do i fix it?
I used this to arrive at solution, this works fine. I will mark it as accepted answer. Please let me know other wise.
JSONObject xmlJSONObj = XML.toJSONObject(response);
JSONArray jsonArray = new JSONArray();
JSONObject data = xmlJSONObj.getJSONObject("data");
JSONObject objArr = data.optJSONObject("countries");
if (objArr != null) {
jsonArray.put(objArr);
data.putOpt("countries", jsonArray);
}

How to create JSON format from Realm "Results" using Object Mapper

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

Parse an entire JSON array into a table using 1 key

I need some help with parsing JSON in Swift.
[{"Database":"information_schema"}
{"Database":"Tonysnasa"},
{"Database":"camaleonsystems"},
{"Database":"camaleonsystems_back"},
{"Database":"camaleonsystemsfortest"}]
^ - Above is my JSON
v - Below is my Swift code.
let jsonDB: String! = jsonResult[0]["Database"] as NSString
println(jsonDB)
self.DBList.append(jsonDB)
I want to parse all of the "Database:" entries. When I try the method above, I am only able to parse information_schema.
How can I parse all the "Database:"'s into my table?
looks like it is an array of dictionaries,to get them all you should be able to use:
var jsonDB : [Dictionary<String, String>] = jsonResult
for currentDictionary in jsonDB{
var currentEntry = currentDictionary["Database"] as String
println(currentEntry)
self.DBList.append(currentEntry)
}

Check Dictionary WIth ObjectForKey IsEqualToString not working

i have this code and searched the internet and find it ok but its not working with me
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
.....
NSLog(#"%#",[dict objectForKey:#"STATUS"]);
if ([[dict objectForKey:#"STATUS"] isEqualToString:#"Y"]) {
NSLog(#"Done");
}
The NSLog Shows Y Which Should Work With if statment
When you do:
[dict setObject:[arr objectAtIndex:1] ...
i think this is adding the strings to the dictionary as objects. The NSLog line is working because NSLog sends each object it is passed the "description" message to convert it to its string value. you can do the same thing.
try changing this:
if ([[dict objectForKey:#"STATUS"] isEqualToString:#"Y"])
to this:
if ([[[dict objectForKey:#"STATUS"] description] isEqualToString:#"Y"])
That would get the string value of the object returned by objectForKey: before doing the comparison.
If you think there might be a white space throwing off the compare, trim the string before comparing, like this:
if ([[[dict objectForKey:#"STATUS"] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:#"Y"])