How to get particular value from JSON object in flutter? - json

I wanted to get value from the API JSON object. My API JSON response is like this.
{
"jobs": [
{
"id": 1,
"user_id": "10",
"job_id": "1",
"experience": "12",
"salary": "1122378"
"job": {
"id": 1,
"title": "PHP SENIOR DEVELOPER",
"company_name": "Envato",
}
}
]
}
I wanted to get the title from the job JSON object. How can we get this value in flutter?

String jobTitle = json['jobs'][0]['job']['title'];

You can achieve this by doing the followng
final Map<String, dynamic> response = {
"jobs": [
{
"id": 1,
"user_id": "10",
"job_id": "1",
"experience": "12",
"salary": "1122378",
"job": {
"id": 1,
"title": "PHP SENIOR DEVELOPER",
"company_name": "Envato",
}
}
],
};
final List<Map<String, dynamic>> jobs = response['jobs'];
final Map<String, dynamic> job = jobs.first['job'];
final String jobTitle = job['title'];
print(jobTitle);

if you get title of the job inside jobs section try below code :
var response = jsonDecode(response.body);
var title = response['jobs'][0]['job']['title'];

You can use https://app.quicktype.io/ to generate the deserialization, so you can handle it by models to prevent errors.
Check: https://flutter.dev/docs/development/data-and-backend/json

Related

I want to parse complex JSON in Flutter with arrays of strings, then display inside another listview

So I want to take out the first letter in the username, that's inside users, for every single list view.builder cell!
My problem is that I can't find any good way to serialize son that has a list of objects inside it and it has become a real problem!
For example we will have a listview with all the projects like this one, then display the names of the members inside every cell. Like in this case: The name will be: "test med teacher chat", and the members will be: "hugo", and "studentone"!
This is what I am thinking but the letter being the first letter of every users username!
JSON:
[
{
"id": 81,
"users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
},
{
"username": "studentone",
"fullname": "Student One"
}
],
"title": "test med teacher chat",
"description": "This project does not have a description.",
"subject": "No subject",
"deadline": "2019-01-06",
"days_left": "98 days ago",
"overview_requests": [
{
"id": 28,
"user": {
"username": "hugo",
"fullname": "Hugo Johnsson"
},
"group": 81
}
]
},
FUTURE:
Future<List<Project>> _getProjects() async {
var data = await http.get(
"http://studieplaneraren.pythonanywhere.com/api/projects/${UserLog().Username}/?format=json");
var jsonData = json.decode(data.body); //an array of json objects
List<Project> allProjects = [];
for (var JData in jsonData) {
Project project = Project(
JData["id"],
JData["title"],
JData["description"],
JData["deadline"],
JData["subject"],
JData["days_left"],
JData["users"]);
allProjects.add(project);
}
return allProjects;
}
DEFINING:
class Project {
final int id;
final String title;
final String description;
final String deadline;
final String subject;
final String days_left;
final List users;
Project(
this.id,
this.title,
this.description,
this.deadline,
this.subject,
this.days_left,
this.users
);
}
I'm not quite sure if I understood what you are looking for, but if you are trying to find a way to parse that json so you can get always the first letter for each username in the list, you just need to understand the structure of the json and that you are getting and make sure that you get the desired field as you usually would do.
I made you a little example using the DartPad and also added a few more usernames to your json.
The data
const List<Map<String,dynamic>> map = [
{
"id": 81,
"users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
},
{
"username": "studentone",
"fullname": "Student One"
},
{
"username": "anotherStudent",
"fullname": "Student Two"
},
{
"username": "oneMore",
"fullname": "Student Three"
},
{
"username": "isItEnough",
"fullname": "Student N"
}
],
"title": "test med teacher chat",
"description": "This project does not have a description.",
"subject": "No subject",
"deadline": "2019-01-06",
"days_left": "98 days ago",
"overview_requests": [
{
"id": 28,
"user": {
"username": "hugo",
"fullname": "Hugo Johnsson"
},
"group": 81
}
]
}
];
Getting the data
void main() {
map.forEach((element) {
final List<Map<String,dynamic>> users = element['users'] as List;
users.forEach((user){
final String firstUsernameLetter = user['username'][0];
print('First letter of ${user['username']}: $firstUsernameLetter');
});
});
}
Output
First letter of hugo: h
First letter of studentone: s
First letter of anotherStudent: a
First letter of oneMore: o
First letter of isItEnough: i

How to get the the node object or array from JSON based on excel sheet data using groovy?

Lets say I have the following JSON :-
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
And, I am passing the value of author from excel sheet to check if that author is present or not. If that author is present inside JSON, then that that particular array node only and remove other from the JSON.
For Example:- I am passing "author" value as "Herbert Schildt" from excel sheet. Now this value is present inside JSON, So, I need this particular array node to be printed and rest all should be removed. Like this:-
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
}
Can it be done using groovy? I have tried with HashMap but couldn't get through.
It's quite easy using groovy:
def text = '''{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
'''
def result = groovy.json.JsonOutput.toJson(
[book: new groovy.json.JsonSlurper().parseText(text).book.findAll{it.author == "Herbert Schildt"}]
)
println result
You may try this ways json search
var json = '{"book":[{"id":"01","language":"Java","edition":"third","author":"Herbert Schildt"},{"id":"07","language":"C++","edition":"second","author":"E.Balagurusamy"}]}';
var parsed = JSON.parse(json);
var result = {};
result.book = [];
var author = "Herbert Schildt";
parsed.book.map((i, j) => {
if(i.author == author) {
result.book.push(i);
}
});
console.log(result)

Get "id" value from httpget json response

Below is my JSON output received post the HttpGet successful execution.
{
"results": [{
"id": "1310760",
"type": "page",
"status": "current",
"title": "UniversalProfile Release Test",
"extensions": {
"position": 9
},
"_links": {
"webui": "/display/ds/UniversalProfile+Release+Test",
"tinyui": "/x/KAAU",
"self": "http:1310760"
},
"_expandable": {
"container": "/rest/api/space/ds",
"metadata": "",
"operations": "",
"children": "/rest/api/content/1310760/child",
"history": "/rest/api/content/1310760/history",
"ancestors": "",
"body": "",
"version": "",
"descendants": "/rest/api/content/1310760/descendant",
"space": "/rest/api/space/ds"
}
}],
"start": 0,
"limit": 25,
"size": 1,
"_links": {
"self": "UniversalProfile+Release+Test",
"base": "https://alim4azad.atlassian.net/wiki",
"context": "/wiki"
}
}
I am trying to extract the value for "id" but have been unsuccessful so far.
If your JSON is in the variable output in Javascript, it'd be :
output.results[0]["id"]
Like console.log(output.results[0]["id"]).
Your results section contains arrays. You want the first (0), and then the key id.
Looking at that resulting JSON hurts my brain.
Assuming you are using JavaScript, try this: output.results[0]['id']
Try This:
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = jsonArray.getJSONObject(0).getString("id");
Finally i found a solution for it . Below is the solution.
JSONArray results = getbodyPage.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
Long id = first.getLong("id"); // Get id of the found page
System.out.println("INFO : Found ID - " + id);
Thank you all for your valuable inputs.

Unable to construct java object from json

Can any body tell me Java class structure equivalent to below json:
{
"status": "OK",
"data":
{
"group_id":2758,
"0":
{
"id": "2758-1",
"customid": "1",
"customid1": "",
"customid2": "",
"mobile": "9190********",
"status": "AWAITED_DLR",
},
"1":
{
"id": "2758-2",
"customid": "2",
"customid1": "",
"customid2": "",
"mobile": "9190********",
"status": "AWAITED_DLR",
}
...
}
"message": "Campaign Submitted successfully"
}
Unable to decide the structure of data object as it contains group_id and list of other object.
You can make a first class which represents your structure with :
an Int : group_id
an ArrayList : data, that contains objects of type Item
Then you create the second class Item that represents the structure of "0" and "1".
If you want to keep the label "0", "1" you can make the type of data an Hashmap<String,Item> instead of ArrayList.
You could use a map:
class Data {
int group_id;
Map<Integer, InnerObject> map = new HashMap<>();
}
Data data = new Data();
data.group_id = 2758;
data.map.put(0, innerObject0);
data.map.put(1, innerObject1);

Liferay API update Data with JSON

I am working on an API for my Portal, to provide users the ability to update there data via API directly from there internal Systems.
Liferay 6.2 bundle Tomcat. (for api call testing I use soapUI)
The get Methods work fine, (I have getAll, and getByID). getByID returns a JSON Object like this:
{
"ID": "ORGANIZATIONID",
"type": "ORGANIZATIONTYPE",
"name": "ORGANIZATIONNAME",
"URI": "ORGANIZATIONNAMEURI"
"date of inclusion": "INCLUTIONDATE",
"last activities": "LASTMODIFIEDDATE",
"address": {
"name of host institution": "NAMEOFHOSTINSTITUTE",
"street1": "STREET1",
"street2" : "STREET2",
"zip": "ZIP",
"city": "CITY",
"country": "COUNTRY",
},
"url": [{"ORGANIZATIONURL"}],
"main contact": {
"first name": "FIRSTNAME",
"last name" : "LASTNAME",
"phone": "PHONE",
"email": "MAINCONTACTEMAIL"
},
"type of host institution" : "TYPEOFHOSTINSTITUTE",
"diseases": [
{
"name": "DISEASENAME1",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
},
{
"name": "DISEASENAME2",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
}
]
}
I would like to have an API for Updating the diseases information for an organization. I have created a URL service where everything is in the url as parameters, but I would like to have it that the in the url only the id parameter is send and the rest of the information in a JSON object. Like:
/api/jsonws/....-portlet...../updateregbb/organization-id/16016/
and the data:
{
"ID": "ORGANIZATIONID",
"diseases": [
{
"name": "DISEASENAME1",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
},
{
"name": "DISEASENAME2",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
}
]
}
But I could not find a solution how I can read the JSON data:
#JSONWebService(value = "updateregbb", method = "POST")
public void updateregbb2(long organizationId, Map jsondata) {
#JSONWebService(value = "updateregbb", method = "POST")
public void updateregbb(long organizationId, JSONObject json) {
How can I get the Data into my function?
Thanks for the help,
Best
Robert