parse jsonarray using gson - json

I am trying to parse below JSON data and I get the data from remote server. I do a HTTP get to pull this data. I get "java.lang.IllegalStateException:Not a JSON Object: [{.."
I use gson to parse the data and get the fields.("endPointName")
Code:
public void getDevices() throws Exception{
// createHttpClient();
ContentExchange contentExchange = new ContentExchange(true);
contentExchange.setMethod("GET");
contentExchange.setURL("http://10.37.14.XX:8080/api/clients");
// contentExchange
httpClient.send(contentExchange);
if (contentExchange.waitForDone() == HttpExchange.STATUS_COMPLETED) {
System.out.println("##Sucesss");
int status = contentExchange.getStatus();
System.out.println(contentExchange.getResponseFields().getStringField("Content-Type"));
String responseContent = contentExchange.getResponseContent();
getAEDetails_gson(responseContent);
}else{
System.out.println("##failed");
}
}
private void getAEDetails_gson(String responseContent) throws Exception {
JsonElement jelement = new JsonParser().parse(responseContent);
JsonObject rootobj = jelement.getAsJsonObject();
JsonArray paymentsArray = rootobj.getAsJsonArray();
for (JsonElement pa : paymentsArray) {
JsonObject paymentObj = pa.getAsJsonObject();
String quoteid = paymentObj.get("endpoint").getAsString();
System.out.println("name is " + quoteid);
}
}
Sample Json(response content)
[
{
"endpoint":"testclient",
"registrationId":"H9eTBcZbGf",
"registrationDate":"2017-01-20T00:00:17-05:00",
"lastUpdate":"2017-01-20T00:00:17-05:00",
"address":"10.37.3.24:56730",
"lwM2mVersion":"1.0",
"lifetime":300,
"bindingMode":"U",
"rootPath":"/",
"objectLinks":[
{
"url":"/",
"attributes":{
"rt":"123",
"ct":1543
}
},
{
"url":"/1/0",
"attributes":{
}
},
{
"url":"/1024/12",
"attributes":{
}
}
],
"secure":false,
"additionalRegistrationAttributes":{
}
},
{
"endpoint":"test2",
"registrationId":"1xqmsOx2QH",
"registrationDate":"2017-01-20T00:00:54-05:00",
"lastUpdate":"2017-01-20T00:00:54-05:00",
"address":"10.37.3.24:56830",
"lwM2mVersion":"1.0",
"lifetime":300,
"bindingMode":"U",
"rootPath":"/",
"objectLinks":[
{
"url":"/",
"attributes":{
"rt":"oma.lwm2m",
"ct":1543
}
},
{
"url":"/1/0",
"attributes":{
}
},
{
"url":"/1024/12",
"attributes":{
}
}
],
"secure":false,
"additionalRegistrationAttributes":{
}
}
]

Related

_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>

hi I am still learning flutter and I am struggling to understand and fix this problem.
I am using dio to retrieve data from api to pass it to repository then to the cubit and then the ui.
when ever I press button that takes me to screen that suppose to show data that come api.
gives me this error.
debug counsel
flutter: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>'
Json respons
{
"chapters": [
{
"id": 114,
"revelation_place": "makkah",
"revelation_order": 21,
"bismillah_pre": true,
"name_simple": "An-Nas",
"name_complex": "An-Nās",
"name_arabic": "الناس",
"verses_count": 6,
"pages": [
604,
604
],
"translated_name": {
"language_name": "english",
"name": "Mankind"
}
}
]}
my model
class ChapterModel {
List<Chapters>? chapters;
ChapterModel({this.chapters});
ChapterModel.fromJson(Map<String, dynamic> json) {
if (json['chapters'] != null) {
chapters = <Chapters>[];
json['chapters'].forEach((v) {
chapters!.add(new Chapters.fromJson(v));
});
}
}
}
class Chapters {
int? id;
String? revelationPlace;
int? revelationOrder;
bool? bismillahPre;
String? nameSimple;
String? nameComplex;
String? nameArabic;
int? versesCount;
List<int>? pages;
TranslatedName? translatedName;
Chapters(
{this.id,
this.revelationPlace,
this.revelationOrder,
this.bismillahPre,
this.nameSimple,
this.nameComplex,
this.nameArabic,
this.versesCount,
this.pages,
this.translatedName});
Chapters.fromJson(Map<String, dynamic> json) {
id = json['id'];
revelationPlace = json['revelation_place'];
revelationOrder = json['revelation_order'];
bismillahPre = json['bismillah_pre'];
nameSimple = json['name_simple'];
nameComplex = json['name_complex'];
nameArabic = json['name_arabic'];
versesCount = json['verses_count'];
pages = json['pages'].cast<int>();
translatedName = json['translated_name'] != null
? new TranslatedName.fromJson(json['translated_name'])
: null;
}
}
my dio
class ApinWebServices {
static late Dio dio;
static init() {
BaseOptions options = BaseOptions(
baseUrl: baseUrl,
queryParameters: {'language': 'ar'},
receiveDataWhenStatusError: true,
);
dio = Dio(options);
}
Future<List<dynamic>> getALLJuzQuran() async {
try {
Response response = await dio.get('chapters');
return response.data;
} catch (e) {
print(e.toString());
return [];
}
}
}
my repository
class ChapterRepository {
final ApinWebServices apinWebServices;
ChapterRepository(this.apinWebServices);
Future<List<ChapterModel>> getALLJuzQuran() async {
final juzQuran = await apinWebServices.getALLJuzQuran();
return juzQuran.map((e) => ChapterModel.fromJson(e)).toList();
}
}
my cubit
class JuzquranCubit extends Cubit<HomeState> {
final ChapterRepository chapterRepository;
late List<ChapterModel> juzQuran = [];
JuzquranCubit(this.chapterRepository) : super(HomeInitial());
List<ChapterModel> getALLJuzQuran() {
chapterRepository.getALLJuzQuran().then((chapters) {
emit(JuzQuranLoaded(chapters: chapters));
this.juzQuran = juzQuran;
});
return juzQuran;
}
}
In your ApinWebServices, you are using
Dio.get('chapters');
which is not a property of Dio, as your data is json use
return response.data['chapters'];

Extract parameters from nested Json

I have an json string, which looks like this:
{
\"request\": {
\"requestId\": \"dd92f43ec593d2d8db94193b7509f5cd\",
\"notificationType\": \"EntityAttribute\",
\"notificationSource\": \"ODS\"
},
\"entityattribute\": {
\"entityId\": \"123\",
\"attributeType\": \"DATE_OF_BIRTH\"
}
}
I want to deserialized entityattribute to an object:
public class EntityAttributeNotification {
private String attributeType;
private String entityId;
}
One way is to extract entityId and attributeType first using the json path(i.e entityattribute/entityId)and create an object EntityAttributeNotification.
I want to know if there is a way to directly deserialized entityattribute to EntityAttributeNotification.
I have also tried with JsonMixin annotation but this does not apply here.
Through the following method you can extract Parameters and Values of nested JSON .
const object1 ={
"request": {
"requestId": "dd92f43ec593d2d8db94193b7509f5cd",
"notificationType": "EntityAttribute",
"notificationSource": "ODS"
},
"entityattribute": {
"entityId": "123",
"attributeType": "DATE_OF_BIRTH"
}
};
var keys = [];
for (let [key, value] of Object.entries(object1)) {
if(typeof value == 'object'){
keys.push(key);
for (let [key1, value1] of Object.entries(value)) {
keys.push(key1);
}
}
else{
keys.push(key);
}
}
console.log(keys);

How to map json entities?

There is a way to map json objects in react-native? For example, let's say I receive the following object:
{
"dados": {
"ultimaAtualizacao": {
"nome": "Lala"
}
"nascimento": "01/01/2001"
}
}
I want to map it like this:
{
"data": {
"lastUpdate": {
"name": "Lala"
}
"dob": "01/01/2001"
}
}
Considering that fetch returns the first object, this would be possible doing the following code:
myService.get(url).then(response => this.mapObject(response, []));
//Considering state is initialized and I have the mapedEntity to return correct properties
mapObject(jsonObject, parentProperty) {
for (let property in jsonObject) {
if (Array.isArray(jsonObject[property])) {
this.mapArray(jsonObject[property], [...parentProperty,property]); //Would be something like mapObject function
} else if (typeof jsonObject[property] === 'object') {
this.mapObject(jsonObject[property],[...parentProperty,property]);
} else {
let prop = this.state;
for(let k of parentProperty) {
prop = prop[mapedEntity[k]];
}
prop[entidadeMapeada[property]] = jsonObject[property];
}
}
}
There is someway simplier to achieve this?

How to deserialize a dart list into json objects?

So basically I want to deserialize a list into json objects and save it to a file.
This is my code for my model.
class NotesList {
final List<Note> notes;
NotesList({
this.notes,
});
factory NotesList.fromJson(List<dynamic> parsedJson) {
List<Note> notes = new List<Note>();
notes = parsedJson.map((i)=>Note.fromJson(i)).toList();
return new NotesList(
notes: notes
);
}
}
class Note {
String title;
String body;
Note({
this.title,
this.body
});
factory Note.fromJson(Map<String, dynamic> json) {
return new Note(
title: json['title'] as String,
body: json['body'] as String,
);
}
}
class Storage {
Future<String> get localPath async {
final dir = await getApplicationDocumentsDirectory();
return dir.path;
}
Future<File> get localFile async {
final path = await localPath;
return File('$path/notes.json');
}
Future<File> writeData(NotesList content) async {
final file = await localFile;
return file.writeAsString("$content");
}
Future<File> clearData() async {
final file = await localFile;
return file.writeAsString("");
}
Future<String> _loadNoteAsset() async {
return await rootBundle.loadString('assets/notes.json');
}
Future<NotesList> loadNotes() async {
String jsonNotes = await _loadNoteAsset();
final jsonResponse = json.decode(jsonNotes);
NotesList notesList = NotesList.fromJson(jsonResponse);
print("First note title: " + notesList.notes[0].title);
return notesList;
}
void writeToFile(String title, String body, int index) async {
print("Writing to file!");
NotesList notesList = await loadNotes();
notesList.notes[index].title = title;
notesList.notes[index].body = body;
writeData(notesList);
print("From writeToFile function $index index title: " + notesList.notes[index].title);
print("From writeToFile function $index index body: " + notesList.notes[index].body);
}
void fileData() async {
try {
final file = await localFile;
String body = await file.readAsString();
print(body);
} catch (e) {
print(e.toString());
}
}
}
My json is structured such as
[
{
"title": "Title 1",
"body": "Greed body"
},
{
"title": "Title 2",
"body": "Greed body"
},
{
"title": "Title 3",
"body": "Greed body"
},
{
"title": "Title 4",
"body": "Greed body"
}
]
The primary function I want to deserialize the list is in the writeToFile function in the Storage class.
You can use dart convert for example.
Your writeData method could look like this. Regard that I also changed the type of the content parameter of writeData from NotesList to List
import 'dart:convert';
...
Future<File> writeData(List content) async {
final file = await localFile;
jsonText = jsonEncode(content.notes);
print("This text will be wirtten to file: " + jsonText);
return file.writeAsString(jsonText);
}

while using JsonRequestBehavior in web api giving error saying cannot convert to json.serializer

I am getting the following compilation error:
cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'
code
public class PondController : ApiController
{
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
You are trying to use code snippet from ASP.NET MVC in ASP.NET WebAPI controller. In WebAPI the results and methods have different signatures. Try following:
public JsonResult<object> Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json((object)new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } });
}
}
catch (Exception Ex)
{
}
return Json((object)new { success = false });
}