Json Parser error in React native - android

Hello I need a solution for multiple json post through react native since I'm new in React native. Here is my new json data I need to post
[
{
"rollno": "10",
"typeofattendence": 1
},
{
"rollno": "10021",
"typeofattendence": 0
}
]
Here is my fetch data please note I can post single json data not able to post multiple.Here is my code
body: JSON.stringify({
rollno: this.state.data,
typeofattendence: this.state.value
})` `body: JSON.stringify({
rollno: this.state.data,
typeofattendence: this.state.value
})
Please help me . Here you can see I can post single json object but how i post inside array multiple object . Thanks in advance

You should store your object in an array first.
For example.
let data = [];
data.push({
rollno: this.state.data,
typeofattendence: this.state.value
});
and when you want to send it to the server
body: JSON.stringify(data);

You can use:
var myarray = [];
var myJSON = "";
var item = {
"rollno": "10",
"typeofattendence": 1
};
myarray.push(item);
item = {
"rollno": "10021",
"typeofattendence": 0
}
myarray.push(item);
myJSON = JSON.stringify({myarray: myarray});
As this http://jsfiddle.net/jensbits/MWSeg/ toturial says.

Related

How to retrieve the list of all GitHub repositories of a person? parsing json list with no key value

I know this question has been answered at this post with same question. however, my question is the Json response by the most upvoted answer will be a json list with no key value.
(you can also check the sample json from the official github website)
I am using Moshi library to parse json. However, I have no idea how to parse that Json list whose key value is not set.(only a list present in the Json with no Key value for that list)
this is what it looks like though
[
{
"id": 1296269,
"node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
"...": "...",
...
},
{
"id": 1296255,
"node_id": "somevalue",
"...": "...",
}
...
]
since the purpose of asking this question is to get a list of repositories of a user, you could leave any code snippet to get that type of list Json to Kotlin data class.
I appreciate your help in advance.
Try this one for Array list
inline fun <reified T> Any?.getResponseInArrayList(): ArrayList<T?>? {
return try {
val token: TypeToken<ArrayList<T>> = object : TypeToken<ArrayList<T>>() {}
val json = Gson().toJson(this)
Gson().fromJson(json, token.type)
} catch (e: Exception) {
Log.e("GSON ERROR ", "" + e.message)
null
}
}
use like this
val model = yourJsonString.getResponseInArrayList<YouJsonModel>()

The provided '#microsoft.graph.aadUserConversationMember' for 'odata.type' is not valid for this operation

I have a mysterious issue that I don't understand. I'd like to do an application that can send a Teams (Microsoft Teams) message to a specific user.
Furthermore, I can achieve this without trouble using the API (with Postman).
As you can see, I don't have any issue to do the request.
However, when I do this with my app (using Flutter) I get an error 400 with this message :
{
"error": {
"code": "BadRequest",
"message": "The provided '#microsoft.graph.aadUserConversationMember' for 'odata.type' is not valid for this operation., The provided '#microsoft.graph.aadUserConversationMember' for 'odata.type' is not valid for this operation.",
"innerError": {
"date": "2022-07-15T13:58:13",
"request-id": "99a5b654-d137-4c4f-9473-234747b32c42",
"client-request-id": "99a5b654-d137-4c4f-9473-234747b32c42"
}
}
}
Obviously, my access token is exactly the same as well as permissions to achieve this request. User's IDS are also the same.
What I am doing:
The request
headers: contains the token and the responseType
final url = Uri.https('graph.microsoft.com', "/v1.0/chats");
final body = ChatMemberDto(
personId: personId,
visitedPersonId: visitedPersonId)
.toJsonStr();
var response = await http.post(url, headers: _headers, body: body);
ChatMemberDto
I know, not well-designed ;)
class ChatMemberDto {
String personId;
String visitedPersonId;
ChatMemberDto({required this.personId, required this.visitedPersonId});
String toJsonStr() {
var data = {
"chatType": "oneOnOne",
"members": [
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind":
"https://graph.microsoft.com/v1.0/users('$personId')"
},
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind":
"https://graph.microsoft.com/v1.0/users('$visitedPersonId')"
}
]
};
return jsonEncode(data);
}
}
I have followed the documentation described here : https://learn.microsoft.com/en-us/graph/api/chat-post?view=graph-rest-1.0&tabs=http
I guess the issue come from my code, because I can do it with Postman. But I can’t understand why??
PS: I've tested it on Android Emulators and real Android devices
Thanks in advance for your help :)
I think the issue is with the conversion to string
Can you try like this and check if it is working
class ChatMemberDto {
String personId;
String visitedPersonId;
ChatMemberDto({required this.personId, required this.visitedPersonId});
String toJsonStr() {
var data = {
"chatType": "oneOnOne",
"members": [
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind": "https://graph.microsoft.com/v1.0/users($personId)"
},
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind":
"https://graph.microsoft.com/v1.0/users($visitedPersonId)"
}
]
};
return jsonEncode(data);
}
}
I've found my mistake. I post here in case someone gets the same error as me.
var headers = {
'Authorization': 'Bearer XXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
var request = http.Request('POST', Uri.parse('https://graph.microsoft.com/v1.0/chats'));
request.body = '''{"chatType":"oneOnOne","members":[{"#odata.type":"microsoft.graph.aadUserConversationMember","roles":["owner"],"user#odata.bind":"https://graph.microsoft.com/v1.0/users(\'XX-XXX-XXXX-XXX\')"},{"#odata.type":"#microsoft.graph.aadUserConversationMember","roles":["owner"],"user#odata.bind":"https://graph.microsoft.com/v1.0/users(\'XX-XXX-XXXX-XXX\')"}]}''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
I've used another lib. Don't really know why it is working with this way and not with the other (see my question) ??
But anyway, this solves the problem!

Retrofit Kotlin and getting an Array?

Anyone here can give me a small hand with Retrofit? I am trying to get an Array from PHP.
This is my Response in Kotlin:
class QuestionnairesResponse (val status: Boolean, val message:String, val questionnaires: List<Questionnaire>)
Questionnaire class:
data class Questionnaire(
val id: Int,
val title: String,
val questions: List<Question>
)
Question class:
data class Question (
val id: Int,
val text: String
)
My JSON array output:
{
"questionnaires":[
{
"id":"1",
"title":"Are you hungry?",
"questions":{
"id":"1",
"text":"How is your passion? "
}
},
{
"id":"2",
"title":"How are you feeling?",
"questions":{
"id":"1",
"text":"How is your passion? "
}
},
{
"id":"5",
"title":"Is testing working?",
"questions":{
"id":"4",
"text":"How is the testing?"
}
}
],
"status":true,
"message":"Succefully got questionnaires!!!"
}
However, it seems it doesn't get the 'questions' part and it results in a failure. The strange thing is that If I change it to 'question' instead of 'questions' it doesn't result in a failure, and it gets the questionnaire details as ID and title, but stil; the question array is empty.
What is going wrong here? I can't seem to find the problem.
UPDATE: My backend needs to be fixed as questions need to be an array.
I just can't seem to wrap my head around on how to fix this issue when getting the data from MySQL....
My PHP code:
$sql = "SELECT questionnaires.id QuestionnaireId, questionnaires.title QuestionnaireTitle, questions.id QuestionId, questions.text Question
FROM questionnaires INNER JOIN questionnaireshasquestions qa ON qa.idQuestionnaire = questionnaires.id
INNER JOIN questions ON questions.id = qa.idQuestion";
$conn=$dbh->prepare($sql);
$conn->execute();
$result = $conn->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
while ($row = $conn->fetchAll()) {
$endResult['questionnaires']= $row;
}
//echo json_encode($endResult);
$idd = null;
$test = [];
foreach ($endResult['questionnaires'] as $questionnaire) {
if ($idd != $questionnaire[0]) {
$idd = $questionnaire[0];
$test['questionnaires'][] = [
'id' => $questionnaire[0],
'title' => $questionnaire[1],
'questions' => [
'id' => $questionnaire[2],
'text' => $questionnaire[3]
]
];
}
}
One questionnaire can have multiple questions.

Can't put a json on a Map on Flutter

I'm trying to get the data from a json and save into a map to use the data on my app, but i cant make it work.
Here´s the json example:
[
{
"Codigo_Produto": 2025,
"Qtde": 4,
"Descricao": "SERVIÇO DE ALINHAR EIXOS",
"Codigo": 3862,
"CodOS": 3862,
"Numero_da_OS": "3862"
},
{
"Codigo_Produto": 2423,
"Qtde": 4,
"Descricao": "SERVIÇO DE CAMBAGEM TRAÇÃO/TRUCK",
"Codigo": 3862,
"CodOS": 3862,
"Numero_da_OS": "3862"
}
]
Here is how i try to access the data:
Map<dynamic, dynamic> map =
jsonDecode(response.data);
print(map);
And i get this error:
E/flutter (15734): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
I have also tried making in different ways but everytime i get this error.
What is wrong with my code? Is it because the response is coming insite a array? What is the best way to receive and make this data usable for my app?
The full code on the button that calls the api is here:
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.2:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
print(response.statusCode);
print(response.data);
Navigator.pop(context, true);
},
Your response.data returns list. Check first line of your json, it has list brackets like this [.
You should retrieve your data this way:
final listOfObjects = <String,dynamic>[];
for(var obj in response.data)
{
listOfObjects.add(jsonDecode(obj));
}
return listOfObjects;
You need to change return type of your Future also, to list of your objects.
Using the json.decode you can extract the data directly to map
String responseBody = await rootBundle.loadString("assets/data.json");
var maplist = await json.decode(responseBody).cast<Map<String, dynamic>>();

Laravel display results of an array as single json object

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));

Categories

Resources