Laravel display results of an array as single json object - android

Is there a way I can get my response to be a single object with an array of users using Eloquent?
For instance:
{
"results" : [
{ "email" : "test1#test.ca" },
{ "email" : "test2#test.ca" }
]
}
Current it outputs like this:
[
{
"email": "test1#test.ca",
},
{
"email": "test2#test.ca",
}
]
This is how I'm displaying users from my code:
$users = User::whereIn('number', $numbers)->select('email')->get();
return $users;
Which would be fine but I'm using Volley for Android using JSONObjectRequest but its failing when it tries to parse the JSON because it can't parse the array.

You can try it like this:
$users = User::whereIn('number', $numbers)->select('email')->get();
return Response::json(array('results' => $users));

Related

How To Parse Response of Multiple Types of Single Key

How To Parse Response of Multiple Types?
Key is like (suppose student_list is a key of list types when student_list is empty then it makes as a string like student_list=""), How to manage this types of response using Retrofit? I am using MVVM Model with retrofit.
My Response:
when I get Data into the List
{
"status": 200,
"data": [
{
"prod_month_total": 2989.61,
"product": "GAS"
},
{
"prod_month_total": 39566.22,
"product": "OIL"
},
{
"prod_month_total": 83912.55,
"product": "OTHER"
}
]
}
when List is Empty Then Response:
{"status":404,"data":"No result found"}
I am getting this Error:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 23 path $.data
first create the right model calss use this site http://www.jsonschema2pojo.org
than use
`if( reponce.isSucessful){
if(responce.status==200){
//code here
}
else{
// find the error
}
}else
{
//
}`

Gson - Named Object to Array

In the response from the server, the data is structured as named objects. I'm trying to figure out how I would convert it to an array with the details in specific fields.
Example response from the server.
{
"Value_1": { "Foo": "True", "Bar": "False"},
"Value_2": { "Foo": "False", "Bar": "False"},
"Value_3": { "Foo": "False", "Bar": "True"}
}
Example of preferred converted result from the server.
{[
{"Name": "Value_1",
"Details": [{"Name": "Foo", "Value": "True"},
{"Name": "Bar", "Value": "False"}]},
{"Name": "Value_2",
"Details": [{"Name": "Foo", "Value": "False"},
{"Name": "Bar", "Value": "False"}]},
{"Name": "Value_3",
"Details": [{"Name": "Foo", "Value": "False"},
{"Name": "Bar", "Value": "True"}]}
]}
How do tell gson to convert from the response to the preferred structure?
I was able to accomplish this in a fairly clean method using a custom JsonDeserializer. The main thing is JsonObject.entrySet(), which gives you the key/value pairs of the JsonObject so you can iterate over them.
First, when building your Retrofit client, add your custom JsonDeserializer.
gsonBuilder.registerTypeAdapter(MyModel::class.java, MyModelDeserializer())
And then implement it like this.
class MyModelDeserializer : JsonDeserializer<MyModel> {
override fun deserialize(json : JsonElement, typeOfT : Type?, context : JsonDeserializationContext?) : MyModel {
val jsonObject = json.asJsonObject
// Create a new ArrayList to store the values.
val list = ArrayList<MyModel>()
// Using entrySet, get each key/value pair. "Value_1: {...}"
for (entry in jsonObject.entrySet()) {
val valueName = entry.key // The key, which would be the name "Value_1"
// Creating a new ArrayList to contain all the data.
val vals = ArrayList<Pair<String, Boolean>>()
val values = entry.value.asJsonObject
// Using entrySet again for each value of the Object.
for (entry in values.entrySet()) {
vals.add(entry.key to entry.value.asBoolean)
}
// Create a new MyModel, with the correct name and values.
list.add(MyModel(valueName, vals))
}
return MyModel(list)
}
}

Unable parse the json data in android even by following the actual procedure

iam trying to parse the json data which is shown below.i got output for other Json response by following this procedure but for this i cant get data.
{
"totalResults": 7,
"startIndex": 1,
"hasMoreResults": false,
"itemsPerPage": 10,
"results": [
{
"offering_temp_id": {
"displayName": "Cool Course",
"id": "cours000000000004841",
"course_no": "00006081",
"version": null
},
"delivery_id": {
"displayName": "Instructor-Led",
"id": "eqcat000000000000004"
},
"student_id": {
"id": "emplo000000006156648",
"displayName": "Venkat Rao",
"person_no": "VRAO"
},
"reg_no": "00008341",
"wlist_on": "2017-08-17T08:59:39.843-0400",
"wlist_priority": 5,
"Max_Count": null,
"Current_Count": null,
"is_no_show": false,
"is_walk_in": false,
"offering_action_id": {
"id": "ofapr000000000013441",
"displayName": "00009081"
},
"class_id": {
"id": "class000000000006981",
"displayName": "Cool Course"
},
"elements_to_complete": 0,
"status": "100",
"id": "regdw000000000012581"
},
// total 7 fields
],
"facets": []
}
And iam using the parser procedure as follows
public class EnrollmentParser {
public ArrayList<EnrollmentData> getData(String respnose)//EnrollmentData is my pojo class contains 4 strings and its getters and setters
{
ArrayList<EnrollmentData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(respnose);
JSONArray array = mainObj.getJSONArray("results");
for(int i = 0;i<array.length();i++)
{
EnrollmentData data = new EnrollmentData();
JSONObject resObj = array.getJSONObject(i);
data.setReg_num(resObj.getString("reg_no"));
data.setElements_to_complete(resObj.getString("elements_to_complete"));
data.setW_list_on(resObj.getString("wlist_on"));
data.setW_list_priority(resObj.getString("wlist_priority"));
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
}
when iam trying to display the dataList returned from above method i didnt get any data i got response like
Suggest me any changes that are required to get the response
There is no faulty parsing code, everything is fine (although better use optString).
By default , the toString function will return the type '#' reference value so
You need to override toString in EnrollmentData class to see the actual content inside EnrollmentData object
You can also collect your list objects as single string using
String str = Arrays.toString(yourList.toArray());
How to print out all the elements of a List in Java?
Why don't you use Gson to convert json into object easily instead of getting the field and set them one by one?
You may check out
https://github.com/google/gson

How to POST following data using retrofit

I want to post the following JSON object in a POST request over retrofit
{
"Inputs": {
"input1": {
"ColumnNames": [
"Name",
"Weekday",
"Time",
"Type"
],
"Values": [
[
" ",
"1",
"9:00:34",
"OUTGOING"
],
]
}}
How do I represent this as a GSON object? I have only found very easy examples online (like {'Foo':'bar'} sort). Any help is greatly appreciated
Use http://www.jsonschema2pojo.org/ to generate the java classes
{
"Inputs": {
"input1": {
"ColumnNames": [
"Name",
"Weekday",
"Time",
"Type"
],
"Values": [
[
" ",
"1",
"9:00:34",
"OUTGOING"
]
]
}
}
}
It looks like you have an "input" object, containing a string array (ColumnNames) and a two dimensional string array (Values). You could interpret it as a java model object like the following
class Input {
String[] ColumnNames;
Value[][] Values;
}
You can then use a json library like Gson to convert your json to and from this model object, eg new Gson().fromJson(jsonInput, Input.class).
The json you actually have shown us wraps your Input object in two other objects though, so make sure to handle them appropriately.

json parsing and storing in an arraylist in Phonegap

in my app when the user clicks a button, it hits an url and i use to get a return data in json format as follows
{
"Status":
{
"image":
[
{
"Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316145577.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316145577.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316146270.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316146270.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316146473.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316146473.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316147003.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316147003.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316581422.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316581422.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316694587.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316694587.jpg"
}
]
}
}
i want to do json parsing and store the URLs named under Large to be stored in an Array and URLs named under Small to be stored in another array. I want this to be done using javascript.
For example in my app in another url my json data is to be as follows
{"Status":[{ "Id": "46", "Username": "guru" }]}
For this i use to get the data as
var data = JSON.parse(my_JSON_object);
var id = data.Status[0].Id;
var name = data.Status[0].Username;
But how to parse for the json array mentioned first.
How to do this, pls help me friends
i got the answer by this way
var data = JSON.parse(my_JSON_object);
var image = [];
for(var i=0; i< image.length(); i++)
{
image[i] = data.Status.image[0].Large;
alert(image);
}
alert(image);

Categories

Resources