Access JSON Array without array name - arrays

I have a JSON object:
{
"login_name":"hello#gmail.com",
"login_pass":"abc123",
"created_on":"2021-01-17 19:20:07",
"user_id":"1",
"active":"1"
}
I don't know how to access it because it doesn't have a name.
This is using Volley:
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val obj = JSONObject(response.toString()) // this works and outputs the JSON object
val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
},
{ error ->
Toast.makeText(this#Login, "Error!", Toast.LENGTH_LONG).show()
}
)
I also tried converting the Json object to an array but that didn't work either...
Looked at:
Get JSONArray without array name, How can i write Android Json parsing without array name
EDIT:
val obj = JSONObject(response)
That didn't work for me because:
None of the following functions can be called with the arguments supplied.
(String!) defined in org.json.JSONObject
((MutableMap<Any?, Any?>..Map<*, *>?)) defined in org.json.JSONObject
(JSONTokener!) defined in org.json.JSONObject
But after 2 days of trying, this worked... Didn't think I could just do that
val test = response.getString("login_name")

response is indeed a jsonObject, you could use it without know its name:
String login_name= response.getString("login_name");

You are all most doing it right. Ass i see you convert the object to a string, and thats why you cant access the data afterwards.
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val obj = JSONObject(response) // this works and outputs the JSON object
val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
},
{ error ->
Toast.makeText(this#Login, "Error!", Toast.LENGTH_LONG).show()
}
)
Try this, without the toString() function on response.

Related

Convert to "native" swift data type

I am getting some data from firestore. The problem is that they are in a format that I don't know how to use. This is the data I
receive:
"["TestKey3": <__NSArrayM 0x600002d30b10>(
ArrayElement1,
ArrayElement2,
ArrayElement3
)
, "TestKey5": 12345, "TestKey4": 1, "TestKey2": TestValue2, "TestKey1": TestValue1]
"
And this is the data type:"DataType: Dictionary<String, Any>". Dictionary seems okay normal. I can use dictionary as normal. I need to unwrap Optional and then it is okay.
5 is Int, 4 is Bool, 3 is array, 2 and 1 is string.
The problem is is the array. Even though I have have unwrapped the dictionary, I need to unwrap the array again. It is a __NSArrayM, so I can't use it as a native/swift array, which I want, like using append(). How do I convert it?
This is the script:
static func getData(collectionName: String, documentName: String) {
let docRef = db.collection(collectionName).document(documentName)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data()
guard var output = dataDescription else {
return
}
print("Getting data at: /\(collectionName)/\(documentName)")
print("DataType: \(type(of: output))")
print(output)
} else {
print("Error getting data at: /\(collectionName)/\(documentName)")
}
}
}`
I want to use "completion: #escaping ([String: Any]?) -> Void)" on the function, so it can wait, but don't know what exactly it should be.

how to retrieve values of the map returned by jsonPath().getMap methods of rest assured

how to retrieve values of the map returned by jsonPath().getMap methods of rest assured
I am trying to get the response on below api in Map, which I am able to successfully get but when I try to access the value of key "id" in the below code, I get cast Error on line "String id = test.get("id");"
public void testRestAssured() {
Response apiResponse = RestAssured.given().get("https://reqres.in/api/user/2");
Map<String, String> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
String id = test.get("id");
System.out.println("ID : " + id);
}
Error
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
I tried to do many things like
String id = test.get("id").toString();
or
String id = String.valueOf(test.get("id"));
but nothing helped in resolution
api response is as follows
{
"data": {
"id": 2,
"name": "fuchsia rose",
"year": 2001,
"color": "#C74375",
"pantone_value": "17-2031"
}
}
Try the below code, it is working fine for me:
Response apiResponse = RestAssured.given().get("http://reqres.in/api/user/2");
Map<Object, Object> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
String id = test.get("id").toString();
System.out.println("ID : " + id);
The changes I have done is: change Map of (String, String) to Map (Object, Object) because we know that each key of map is string but value could be of any data type.
I hope it will solve your problem.
Correct code is
Response apiResponse = RestAssured.given().get("http://reqres.in/api/user/2");
Map<Object, Object> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
for (Object e : test.keySet()) {
System.out.println(" Key is " + e + " , value is " + test.get(e));
simply try this:
import com.jayway.restassured.path.json.JsonPath;
JsonPath extractor = JsonPath.from(apiResponse.toString());
String id = extractor.getString("data.id");
You should define Object for map value. Because your json values are different types (String and int).
// define Object type for map values
Map<String, Object> test = apiResponse.jsonPath().getMap("data");
// use casting for assigning
int id = (int) test.get("id");
Do you really need to make from your response map object?
If not you can use this one:
String id = RestAssured.given().get("https://reqres.in/api/user/2")
.then().extract().jsonPath().getString("data.id");

Scala play api for JSON - getting Array of some case class from stringified JSON?

From our code, we call some service and get back stringified JSON as a result. The stringified JSON is of an array of "SomeItem", which just has four fields in it - 3 Longs and 1 String
Ex:
[
{"id":33,"count":40000,"someOtherCount":0,"someString":"stuffHere"},
{"id":35,"count":23000,"someOtherCount":0,"someString":"blah"},
...
]
I've been using the play API to read values out using implicit Writes / Reads. But I'm having trouble getting it to work for Arrays.
For example, I've been try to parse the value out of the response, and then convert it to the SomeItem case class array, but it's failing:
val sanityCheckValue: JsValue: Json.parse(response.body)
val Array[SomeItem] = Json.fromJson(sanityCheckValue)
I have
implicit val someItemReads = Json.reads[SomeItem]
But it looks like it's not working. I've tried to set up a Json.reads[Array[SomeItem]] as well, but no luck.
Should this be working? Any tips on how to get this to work?
import play.api.libs.json._
case class SomeItem(id: Long, count: Long, someOtherCount: Long, someString: String)
object SomeItem {
implicit val format = Json.format[SomeItem]
}
object PlayJson {
def main(args: Array[String]): Unit = {
val strJson =
"""
|[
| {"id":33,"count":40000,"someOtherCount":0,"someString":"stuffHere"},
| {"id":35,"count":23000,"someOtherCount":0,"someString":"blah"}
|]
""".stripMargin
val listOfSomeItems: Array[SomeItem] = Json.parse(strJson).as[Array[SomeItem]]
listOfSomeItems.foreach(println)
}
}

Swift3 how do I get the value of a specific key in a string?

I've got a server response returning
(
{
agreementId = "token.virtual.4321";
city = AMSTERDAM;
displayCommonName = "bunch-of-alphanumeric";
displaySoftwareVersion = "qb2/ene/2.7.14";
houseNumber = 22;
postalCode = zip;
street = "";
}
)
how do I get the value of agreementId? response['agreementId'] is not working. i've tried some example code with .first but I cannot get it working.
Some extra information, I do a http call to a server with alamofire. I try to parse the json to a constant response:
let response = JSON as! NSDictionary
However that returns a error message
Could not cast value of type '__NSSingleObjectArrayI' (0x1083600) to 'NSDictionary' (0x108386c).
So now parse the json to an array, which seems to be working. The code above is what
let response = JSON as! NSArry
print(response)
spits out.
Now I only need to retrieve the value from the key "agreementId" and I have no clue how to do that.
In swift you need to use Swift's native type Array/[] and Dictionary/[:] instead of NSArray and NSDictionary, if you specify the type like above means more specific then the compiler won't complain. Also use optional wrapping with if let or guard let to prevent crash.
if let array = JSON as? [[String:Any]] {//Swift type array of dictionary
if let dic = array.first {
let agreementId = dic["agreementId"] as? String ?? "N/A"//Set default value instead N/A
print(agreementId)
//access the other key-value same way
}
}
Note: If you having more than one object in your array then you need to simply loop through the array to access each dictionary of array.
if let array = JSON as? [[String:Any]] {//Swift type array of dictionary
for dic in array {
let agreementId = dic["agreementId"] as? String ?? "N/A"//Set default value instead N/A
print(agreementId)
//access the other key-value same way
}
}

Swift empty array does not have a member named .insert

I am new to Swift.
I am trying to get some data from a webservice and to loop the JSON data to make a simple array.
DataManager.getDataFromEndpoint{ (endpointData) -> Void in
let json = JSON(data: endpointData)
if let programsOnAir = json["data"]["data"]["on_air"].array{
var onAirArray = []
for onAir in programsOnAir {
var eventName = onAir["event_name"].string
var eventCover = onAir["event_cover"].string
var tuple = (name: eventName!, cover: eventCover!)
onAirArray.insert(tuple, atIndex: 1)
}
println(onAirArray)
}
}
I get an error where the member .insert does not exist
BUt if I init the array like this var onAirArray = [name: "something, cover: "somethingelse"] then it works.
I need to work with empty arrays and I need to be them mutable, because I have no idea what I may get from the JSON given by the API endpoint.
What am I doing wrong?
The problem is with this line:
var onAirArray = []
Since you haven't given the array an explicit type, this is creating a new instance of NSArray, which doesn't have a method called insert. Which is why this is probably the exact error message you're receiving.
'NSArray' does not have a member named 'insert'
To fix this, explicitly state the type of your array.
var onAirArray: [(String, String)] = []

Resources