Getting JSON array of data using POST method using HttpUrlConnection in Android - json

I want to do an API call using HttpUrlConnection for POST as the JSON content looks like this
To POST I need to pass key as id and value as 1234.
{
"message": "Success",
"constituency": [{
"id": "1",
"constituency_name": "abc"
}, {
"id": "2",
"constituency_name": "def"
}]
}
I need to fetch this array of strings. How do I do this?

jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);

Related

How to Get JSON Object Within JSON Array

i want to get avatar_url in actor object. i can get "id" and "type" to show in recyclerview. but avatar_url not show image why?
json url
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i=0; i<response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Article article = new Article();
article.setAvatar_url(jsonObject.getString("avatar_url"));
article.setId(jsonObject.getString("id"));
article.setType(jsonObject.getString("type"));
articles.add(article);
how i get avatar_url from actor field?
and yes i can run because i delete
article.setAvatar_url(jsonObject.getString("avatar_url"));
Thanks
Looking at your JSON, you can see that the "avatar_url" isn't a peer of the "id" and "type".
"id": "11392115556",
"type": "PushEvent",
"actor": {
"id": 8517910,
"login": "LombiqBot",
"display_login": "LombiqBot",
"gravatar_id": "",
"url": "https://api.github.com/users/LombiqBot",
"avatar_url": "https://avatars.githubusercontent.com/u/8517910?"
},
You need to retrieve the "actor" object and then get the "avatar_url" from within that object.

JSON Array Parsing Kafka

I have the following setup:
A Rest endpoint to accept JSON POST request:
I am parsing the request and sending it as a String over Kafka.
But getting parsing errors
A Rest endpoint to accept JSON POST request:
[ { "Name": "Jack", "Id": "314", "Gender": "M" } , { "Name": "John", "Id": "451", "Gender": "M" }, { "Name": "Rita", "Id": "501", "Gender": "F" } ]
I am parsing the request as follows
#RequestMapping(method = RequestMethod.POST, value = "/record")
#ResponseBody
public String process(#RequestBody Map<String, Object>[] payload) throws
Exception {
String str = Arrays.toString(payload)
KafkaProd.toTopic(str);
System.out.println("Payload: " +str);
return "Record Processed";
}
str = Arrays.toString(payload) is changing it into the following format
[ { Name = Jack , Id = 314, Gender = M } , { Name = John, Id = 451,
Gender = M }, { Name = Rita, Id = 501, Gender = F } ]
When I'm trying to parse this string back into json array using json-s
imple :
JSONArray jsonArray = new JSONArray(record.value());
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println("Json Objects : "
+jsonArray.getJSONObject(i).toString());
}
I am getting JSON Parsing error, since the record.value() is not a valid json array
Option 1. How do I convert this to a valid json array?
Option 2. How do I send the json array in a proper format through kafka?
Which of these options do I use?
Instead of String str = Arrays.toString(payload) use a Jackson ObjectMapper to convert the map to a String.

Get value from JSON object having multiple keys

I am having a JSON Object as below:
{
"winame": "123",
"val": "[
{
"gurName": "sds",
"gurType": "",
"crNo": "",
"crissueDate": "",
"dob": "",
"gender": "",
"address": "",
"maritialStatus": "",
"cache": ""
}
]"
}
In which first key is value and second key contains the values of some Java Object type. How to parse the value of 'winame' and 'val' into that java Object.
You can parse JSON with any number of keys.
JSONObject obj = new JSONObject("xyz");
String winame= obj.getJSONObject("winame");
JSONArray arr = obj.getJSONArray("val");
for (int i = 0; i < arr.length(); i++)
{
String gurName = arr.getJSONObject(i).getString("gurName");
String gurType = arr.getJSONObject(i).getString("gurType");
String crNo = arr.getJSONObject(i).getString("crNo");
String crissueDate = arr.getJSONObject(i).getString("crissueDate");
String dob = arr.getJSONObject(i).getString("dob");
String gender = arr.getJSONObject(i).getString("gender");
String address = arr.getJSONObject(i).getString("address");
String maritialStatus = arr.getJSONObject(i).getString("maritialStatus");
String cache = arr.getJSONObject(i).getString("cache");
}

Extract value from array of objects in Postman

I want to extract Id value from the array with objects in Postman and then set it as an environment variable. In case JSON response is an object, the following script works, but not with an array of objects (my array has only one object).
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data.Id);
JSON response:
[
{
"Id": 1287,
"LastName": "Trump",
"FirstName": "Donald",
"MiddleName": "Von",
"City": "New York City",
"Phone": "66 77 88",
"State": "New York",
"Fax": "111-222-333",
"ReferenceId": "12345",
"Active": false,
"CurrentWorkingSchemeId": null
}
]
If it is an array of objects, then just select the first object using index [0] before grabbing the object's key like this:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data[0].Id);
This works like charm!
Basically what i am doing here is, parse the response and from the data array, take id and save it in postman environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++) `
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}

Json.Net: Trimming an object to save web traffic

I have a very complex JSON returning from an API. I need to pass only the "first level" to the client side, without all the nested objects contained in it.
For example:
{
"name": "David",
"age": 5,
"school": {
"name": "Highschool",
"location": "AZ"
}
}
I'd like to pass to the client side only name & age, not "school".
Is there a simple way to do that?
You could parse the JSON into a JObject then copy all the "simple" properties (i.e. those that are not objects and arrays) to a new JObject. Then get the new JSON from the copy.
For example:
string json = #"
{
""name"": ""David"",
""age"": 5,
""school"": {
""name"": ""Highschool"",
""location"": ""AZ""
}
}";
JObject origObj = JObject.Parse(json);
JObject copyObj = new JObject();
foreach (JProperty prop in origObj.Properties())
{
if (prop.Value.Type != JTokenType.Object &&
prop.Value.Type != JTokenType.Array)
{
copyObj.Add(prop.Name, prop.Value);
}
}
json = copyObj.ToString();
Console.WriteLine(json);
The above will output the following:
{
"name": "David",
"age": 5
}