I am looking to merge the list 1 and List 2 inorder to get the expected output as below.
Both the lists are Java classes and also want to add to a new Java class on the expected structure.
I have tried looping through List1 and List2 but in vain.
Also tried using lambda expression but could not get the expected output.
Will post the code that I tried.
Any help is highly appreciated.
List 1(juniorArea):
{
“One”: [
"G13DA"
],
“Two”: [
"G13AA",
"G13AD"
]
}
List 2:
[
{
"subgroupCode": "G13AA",
"productGroup": [
{
"productCode": "G1A",
"productDescription": “Two 1"
},
{
"productCode": "G9B",
"productDescription": “Two 2"
}
]
},
{
"subgroupCode": "G13AD",
"productGroup": [
{
"productCode": "G4A",
"productDescription": “Two 3”
},
{
"productCode": "G9C",
"productDescription": “Two 4”
}
]
},
{
"subgroupCode": "G13DA",
"productGroup": [
{
"productCode": "G5M",
"productDescription": “One 1"
},
{
"productCode": "G9M",
"productDescription": “One 2"
}
]
}
]
Expected Output:
{
"juniorArea": [
{
"juniorAreaDescription": “One”,
"mechandisingGroup": [
{
"productCode": "G5M",
"productDescription": “One 1"
},
{
"productCode": "G9M",
"productDescription": “One 2"
}
]
},
{
"juniorAreaDescription": “Two”,
"mechandisingGroup": [
{
"productCode": "G1A",
"productDescription": “Two 1"
},
{
"productCode": "G9B",
"productDescription": “Two 2"
},
{
"productCode": "G4A",
"productDescription": “Two 3”
},
{
"productCode": "G9C",
"productDescription": “Two 4”
}
]
}
]
}
You will need to make use of Google's gson library to parse your json Strings and also create Additional Classes to hold the data for the same. Save your json String in Files to read the content and convert them to appropriate Objects.
The JSON Strings you have mentioned have error since you are using (“) at many places. Replace them with (") at all locations. This change is very important because if you don't do it you might get Exceptions or undesirable outputs.
Store your Json strings as follows:
List1.txt
{
"One": [
"G13DA"
],
"Two": [
"G13AA",
"G13AD"
]
}
List2.txt
[
{
"subgroupCode": "G13AA",
"productGroup": [
{
"productCode": "G1A",
"productDescription": "Two 1"
},
{
"productCode": "G9B",
"productDescription": "Two 2"
}
]
},
{
"subgroupCode": "G13AD",
"productGroup": [
{
"productCode": "G4A",
"productDescription": "Two 3"
},
{
"productCode": "G9C",
"productDescription": "Two 4"
}
]
},
{
"subgroupCode": "G13DA",
"productGroup": [
{
"productCode": "G5M",
"productDescription": "One 1"
},
{
"productCode": "G9M",
"productDescription": "One 2"
}
]
}
]
You will need to change the file paths of these two while Running the Program
Add the following classes
JuniorArea.class
public class JuniorArea {
private String juniorAreaDescription;
private List<MerchandisingGroup> mechandisingGroup;
public String getJuniorAreaDescription() {
return juniorAreaDescription;
}
public void setJuniorAreaDescription(String juniorAreaDescription) {
this.juniorAreaDescription = juniorAreaDescription;
}
public List<MerchandisingGroup> getMechandisingGroup() {
return mechandisingGroup;
}
public void setMechandisingGroup(List<MerchandisingGroup> mechandisingGroup) {
this.mechandisingGroup = mechandisingGroup;
}
#Override
public String toString() {
return "JuniorArea [juniorAreaDescription=" + juniorAreaDescription + ", mechandisingGroup=" + mechandisingGroup
+ "]";
}
}
JuniorAreaCollection.class
public class JuniorAreaCollection {
private List<JuniorArea> juniorArea;
public List<JuniorArea> getJuniorArea() {
return juniorArea;
}
public void setJuniorArea(List<JuniorArea> juniorArea) {
this.juniorArea = juniorArea;
}
#Override
public String toString() {
return "JuniorAreaCollection [juniorArea=" + juniorArea + "]";
}
}
MerchandisingGroup.class
public class MerchandisingGroup {
private String productCode;
private String productDescription;
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
#Override
public String toString() {
return "MechandisingGroup [productCode=" + productCode + ", productDescription=" + productDescription + "]";
}
}
Product.class
public class Product {
private String subgroupCode;
private List<ProductGroup> productGroup;
public String getSubgroupCode() {
return subgroupCode;
}
public void setSubgroupCode(String subgroupCode) {
this.subgroupCode = subgroupCode;
}
public List<ProductGroup> getProductGroup() {
return productGroup;
}
public void setProductGroup(List<ProductGroup> productGroup) {
this.productGroup = productGroup;
}
#Override
public String toString() {
return "Product [subgroupCode=" + subgroupCode + ", productGroup=" + productGroup + "]";
}
}
ProductGroup.class
public class ProductGroup {
private String productCode;
private String productDescription;
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
#Override
public String toString() {
return "ProductGroup [productCode=" + productCode + ", productDescription=" + productDescription + "]";
}
}
Finally run the follwing Main Class code, to check the output
public class MainRunner {
// Use Path according to your file system
private static String List1Path = "/List1.txt";
// Use Path according to your file system
private static String List2Path = "/List2.txt";
public static void main(String...arg) throws UnsupportedEncodingException, IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String List1Content = new String(Files.readAllBytes(Paths.get(List1Path)), "UTF-8");
Map<String, List<String>> map = new HashMap<>();
map = gson.fromJson(List1Content, new TypeToken<Map<String, List<String>>>() {}.getType());
System.out.println(map);
String List2Content = new String(Files.readAllBytes(Paths.get(List2Path)), "UTF-8");
List<Product> products = gson.fromJson(List2Content, new TypeToken<List<Product>>() {}.getType());
System.out.println(products);
List<JuniorArea> juniorAreas = new ArrayList<>();
for (String s : map.keySet()) {
JuniorArea juniorArea = new JuniorArea();
juniorArea.setJuniorAreaDescription(s);
List<MerchandisingGroup> merchandisingGroups = new ArrayList<>();
List<String> subgroupCodes = map.get(s);
for (String subgroupCode : subgroupCodes) {
for (Product product : products) {
if (product.getSubgroupCode().equals(subgroupCode)) {
List<ProductGroup> productGroups = product.getProductGroup();
for (ProductGroup productGroup : productGroups) {
MerchandisingGroup merchandisingGroup = new MerchandisingGroup();
merchandisingGroup.setProductCode(productGroup.getProductCode());
merchandisingGroup.setProductDescription(productGroup.getProductDescription());
merchandisingGroups.add(merchandisingGroup);
}
}
}
}
juniorArea.setMechandisingGroup(merchandisingGroups);
juniorAreas.add(juniorArea);
}
JuniorAreaCollection collection = new JuniorAreaCollection();
collection.setJuniorArea(juniorAreas);
System.out.println(gson.toJson(collection));
}
}
Output should be printed on your console
{
"juniorArea": [
{
"juniorAreaDescription": "One",
"mechandisingGroup": [
{
"productCode": "G5M",
"productDescription": "One 1"
},
{
"productCode": "G9M",
"productDescription": "One 2"
}
]
},
{
"juniorAreaDescription": "Two",
"mechandisingGroup": [
{
"productCode": "G1A",
"productDescription": "Two 1"
},
{
"productCode": "G9B",
"productDescription": "Two 2"
},
{
"productCode": "G4A",
"productDescription": "Two 3"
},
{
"productCode": "G9C",
"productDescription": "Two 4"
}
]
}
]
}
Related
I have this json:
{
"data":[
{
"id": "Character_Alien",
"name": "Trespasser",
"description": "Invader",
"type": {
"value": "outfit",
"displayValue": "Outfit",
"backendValue": "AthenaCharacter"
},
"rarity": {
"value": "uncommon",
"displayValue": "Uncommon"
},
"series": null,
"set": null,
"introduction": {
"chapter": "2022",
"text": "Introduced in 2022",
"backendValue": 22
},
"images": {
"smallIcon": "https://smallimage.png",
"icon": "https://image.png",
"featured": "https://imagebig.png",
"other": null
},
"variants": null,
"searchTags": null,
"metaTags": null
},
{
"id": "Character_Knowing",
"name": "Sinister",
"description": "He holds your fate.",
"type": {
"value": "outfit",
"displayValue": "Outfit",
"backendValue": "AthenaCharacter"
},
"rarity": {
"value": "rare",
"displayValue": "Rare",
"backendValue": "EFortRarity::Rare"
},
"series": null,
"set": {
"value": "Malice",
"text": "Path.",
"backendValue": "GripHate"
},
"introduction": {
"chapter": "2021",
"backendValue": 22
},
"images": {
"smallIcon": "https://smallimage.png",
"icon": "https://image.png",
"featured": "https://imagebig.png",
"other": null
},
"variants": null,
"searchTags": null,
"metaTags": null
}
]
}
It is a JSON 50000+ lines long this is just 2 of the objects of the JSON. I would like to get the "name", the "images" and the "rarity" values only if the "displayValue" is "Outfit". There are a lot of different displayValues so I want to filter the Outfit value first and then I can figure out how to filter the other ones.
I would like to do it in C# but if it can be done easier using Java I can do it there too(I have basic knowledge on both of them)
I have this in mind:
Foreach object in the json
If the object.displayValue = outfit then
string name = object.name
string imagesmall = object.imagesmall
string image = object.image
string imagebig = object.imagebig
String rariry = object.rarity
If it can be done this way, I then want to generate an image for each outfit with the name and rarity in it as text.
Any links to a similar question would be appreciated, It is the 3rd day that I am looking how to do this and this is my last resort.
.Net 6 (no external libraries needed):
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Linq;
string json = "....."; // Removed for brevity
var results = ((JsonArray)(JsonNode.Parse(json))["data"])
.Where(o => (string)(o["type"]["displayValue"]) == "Outfit")
.Select(o => new
{
Name = (string)o["name"],
ImageSmall = (string)o["images"]["smallIcon"],
Image = (string)o["images"]["icon"],
ImageBig = (string)o["images"]["featured"],
Rarity = (string)o["rarity"]["value"]
});
foreach (var x in results) {
Console.WriteLine(x);
}
Output:
{ Name = Trespasser, ImageSmall = https://smallimage.png, Image = https://image.png, ImageBig = https://imagebig.png, Rarity = uncommon }
{ Name = Sinister, ImageSmall = https://smallimage.png, Image = https://image.png, ImageBig = https://imagebig.png, Rarity = rare }
You can be done this using Newtonsoft.Json NuGet easily. I have used the JSON as the string for the example. You can add your source for the relevant.
In case if you have a larger JSON with more attributes, you can use the Past Special option in Visual Studio to create the object Check Here
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string json = "{" +
"\n\"data\":[\n" +
"{\n\"id\":\"Character_Alien\",\n\"name\": \"Trespasser\",\n\"description\": " +
"\"Invader\",\n\"type\": {\n\"value\": \"outfit\",\n\"displayValue\": \"Outfit\",\n\"backendValue\": " +
"\"AthenaCharacter\"\n},\n\"rarity\": {\n\"value\": \"uncommon\",\n\"displayValue\": \"Uncommon\"\n}" +
",\n\"series\": null,\n\"set\": null,\n\"introduction\": {\n\"chapter\": \"2022\",\n\"text\": \"Introduced in 2022\"," +
"\n\"backendValue\": 22\n}," +
"\n\"images\": {\n\"smallIcon\": \"https://smallimage.png\",\n\"icon\": \"https://image.png\"," +
"\n\"featured\": \"https://imagebig.png\",\n\"other\": null\n},\n\"variants\": null,\n\"searchTags\": null," +
"\n\"metaTags\": null\n},\n{\n\"id\": \"Character_Knowing\",\n\"name\": \"Sinister\"," +
"\n\"description\": \"He holds your fate.\",\n\"type\": {\n\"value\": \"outfit\",\n\"displayValue\": \"Outfit\"," +
"\n\"backendValue\": \"AthenaCharacter\"\n}," +
"\n\"rarity\": {\n\"value\": \"rare\",\n\"displayValue\": \"Rare\",\n\"backendValue\": \"EFortRarity::Rare\"\n}," +
"\n\"series\": null,\n\"set\": {\n\"value\": \"Malice\",\n\"text\": \"Path.\",\n\"backendValue\": \"GripHate\"\n}," +
"\n\"introduction\": {\n\"chapter\": \"2021\",\n\"backendValue\": 22\n},\n\"images\": " +
"{\n\"smallIcon\": \"https://smallimage.png\",\n\"icon\": \"https://image.png\",\n\"featured\": \"https://imagebig.png\"," +
"\n\"other\": null\n},\n\"variants\": null,\n\"searchTags\": null,\n\"metaTags\": null\n}\n]\n" +
"}";
var jsonArr = JsonConvert.DeserializeObject<JsonArr>(json);
var val = jsonArr.Data.Where(w => w.Type.Value == "outfit").Select(s => new Data
{
Name = s.Name,
Rarity = s.Rarity
}).ToList();
Console.WriteLine(json);
Console.ReadKey();
}
}
public class JsonArr
{
[JsonProperty(PropertyName = "data")]
public List<Data> Data { get; set; }
}
public class Data
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "type")]
public DataType Type { get; set; }
[JsonProperty(PropertyName = "rarity")]
public Rarity Rarity { get; set; }
}
public class DataType
{
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
[JsonProperty(PropertyName = "displayValue")]
public string DisplayValue { get; set; }
[JsonProperty(PropertyName = "backendValue")]
public string BackendValue { get; set; }
}
public class Rarity
{
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
[JsonProperty(PropertyName = "displayValue")]
public string DisplayValue { get; set; }
[JsonProperty(PropertyName = "backendValue")]
public string BackendValue { get; set; }
}
I have a JSON array below, I want to be able to set label names that make sense instead of the entity names. Am generating tables dynamically using this data, I want the rows to have names that make more sense to the end user by assigning custom Label names. the recordtype generates new tab names
This is my JSON
[
{
"country": "USA",
"projectId": "USAID2020,
"case": "2014",
"recordType": "Identification",
"itemDetails": [
{
"ItemValue": "023",
"Label": "hA",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "hUM",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "5",
"Label": "hCounty",
"ItemValueLabel": "5",
"Name": "hCounty"
}
]
},
{
"country": "USA",
"projectId": "USAID2020",
"case": "2014",
"recordType": "Eligibility",
"itemDetails": [
{
"ItemValue": "023",
"Label": "hA",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "hUM",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "0005",
"Label": "hPUM",
"ItemValueLabel": "0005",
"Name": "hPUM"
}
]
}
]
This is how I want the labels to appear
[
{
"country": "USA",
"projectId": "USAID2020,
"case": "2014",
"recordType": "Identification",
"itemDetails": [
{
"ItemValue": "023",
"Label": "Area Code",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "Manager Identification",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "5",
"Label": "County Name",
"ItemValueLabel": "5",
"Name": "hCounty"
}
]
},
{
"country": "USA",
"projectId": "USAID2020",
"case": "2014",
"recordType": "Eligibility",
"itemDetails": [
{
"ItemValue": "023",
"Label": "Area Code",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "Manager Identification",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "0005",
"Label": "House Code",
"ItemValueLabel": "0005",
"Name": "hPUM"
}
]
}
]
This is my logic
public ArrayList<Summary> getHouseHoldRecordsByCase(String country, String projectId, String case) {
ArrayList<Summary> documents= new ArrayList<>();
Summary summary = new Summary();
ArrayList<ItemDetails> details = new ArrayList<>();
COVER cover = dataStoreService.getHouseHoldRecordsByCase(country, projectId, caseNumber);
summary.case = caseNumber;
summary.recordType = "Identification";
summary.country = country;
summary.projectId = projectId;
Field[] fields = hsecover.getClass().getDeclaredFields();
for (Field _f:fields){
try {
String val = PropertyUtils.getProperty(hsecover, _f.getName()).toString();
details.add(new ItemDetails(val, _f.getName(), val, _f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
summary.itemDetails = details;
documents.add(summary);
summary = new Summary();
ELIGILITY elig = dataStoreService.getEliByCase(country, projectId, case);
summary.recordType = "Eligibility";
summary.case = case;
summary.country = country;
summary.projectId = projectId;
details = new ArrayList<>();
fields = elig.getClass().getDeclaredFields();
for (Field _f:fields){
try {
String val = PropertyUtils.getProperty(elig, _f.getName()).toString();
details.add(new ItemDetails(val, _f.getName(), val, _f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
summary.itemDetails = details;
documents.add(summary);
}
return documents;
}
public COVER getHouseHoldRecordsByCase(String country, String projectId, String case) {
COVER usa = cover_repository.findByCase(case);
return usa;
}
public ELIGILITY getEliByCase(String country, String projectId, String case) {
ELIGILITY usa = eligility_repository.findByCaseNumber(case);
return usa;
}
My ItemDetails model class
public class ItemDetails {
public String ItemValue;
public String Label;
public String ItemValueLabel;
public String Name;
public ItemDetails(String itemValue, String label, String itemValueLabel, String name) {
ItemValue = itemValue;
Label = label;
ItemValueLabel = itemValueLabel;
Name = name;
}
}
My Summary class
public class Summary {
public String country;
public String projectId;
public String case;
public String recordType;
public ArrayList<ItemDetails> itemDetails;
}
The data comes from a database.
How can I set the label names with names that make sense instead of coming as entity names?
You Can use #JsonProperty("different names") on each fields
Or you can use #JsonSetter("different name") on setter method level.
Using Java 1.8 and Spring Boot 1.5.6.RELEASE.
Am able to obtain a list of items from by parsing /etc/passwd and /etc/group inside an ArrayList & ArrayList.
Need to create the following Rest Endpoint:
HTTP GET /users/<uid>/groups
Return all the groups for a given user.
User:
public class User {
String name;
String password;
Integer uid;
Integer gid;
String comment;
String home;
String shell;
public User(String line) {
String[] items = line.split(":");
if (items.length != 7) {
throw new IllegalArgumentException("Need 7 items from " + line + " and there's only: " + items.length);
}
this.name = items[0];
this.password = items[1];
this.uid = Integer.parseInt(items[2]);
this.gid = Integer.parseInt(items[3]);
this.comment = items[4];
this.home = items[5];
this.shell = items[6];
}
// Getters & Setters omitted for brevity.
}
Group:
public class Group {
private Integer gid;
private String name;
private List<String> members;
public Group(String line) {
String[] items = line.split(":");
this.name = items[0];
this.gid = Integer.parseInt(items[2]);
if (items.length > 3){
this.members = Arrays.asList(items[3]);
}
}
// Getters & Setters omitted for brevity.
}
FileParserUtils:
public class FileParserUtils {
public static List<Group> parseFileForGroups(String line) {
List<Group> groups = null;
try (Stream<String> stream = Files.lines(Paths.get(line))) {
groups = stream.filter(s -> s.charAt(0) != '#').map(Group::new)
.collect(Collectors.toCollection(LinkedList::new));
}
catch (Exception e) {
e.printStackTrace();
}
return groups;
}
}
Service:
#Service
public class UserServiceImpl implements UserService {
#Override
public User findByUid(String line, Integer uid) {
List<User> allUsers = FileParserUtils.parseFileForUsers(line);
for (User user : allUsers) {
if (user.getUid() == uid) {
return user;
}
}
return null;
}
#Override
public List<Group> findByGroupsByUid(String line, Integer uid) {
User specificUser = findByUid(line, uid);
Integer userGid = specificUser.getGid();
List<Group> allGroups = FileParserUtils.parseFileForGroups(line);
List<Group> userGroups = new ArrayList<>();
for (Group group : allGroups) {
if (userGid == group.getGid()) {
userGroups.add(group);
}
}
return userGroups;
}
}
This issue is that not all User uids are the same as the Group's gids (see the gids & uids for "name":"_cyrus"):
Obtain a list of Users (along with their uids & gids):
HTTP GET /myservice/users:
Yields JSON Payload Response:
[
{
"name":"_cyrus",
"password":"*",
"uid":77,
"gid":6,
"comment":"Cyrus Administrator",
"home":"/var/imap",
"shell":"/usr/bin/false"
},
{
"name":"_mailman",
"password":"*",
"uid":78,
"gid":78,
"comment":"Mailman List Server",
"home":"/var/empty",
"shell":"/usr/bin/false"
},
{
"name":"_appserver",
"password":"*",
"uid":79,
"gid":79,
"comment":"Application Server",
"home":"/var/empty",
"shell":"/usr/bin/false"
},
{
"name": "_jabber",
"password": "*",
"uid": 84,
"gid": 84,
"comment": "Jabber XMPP Server",
"home": "/var/empty",
"shell": "/usr/bin/false"
}
]
Groups only have gids (and not uids):
[
{
"gid": 6,
"name": "mail",
"members": [
"_teamsserver"
]
}
{
"gid": 78,
"name": "_mailman",
"members": null
},
{
"gid": 79,
"name": "_appserverusr",
"members": null
},
{
"gid": 30,
"name": "_keytabusers",
"members": [
"_calendar,_jabber,_postfix"
]
}
]
So, when if I try to find all the groups that Jabber belongs to:
http://localhost:8080/MyService/users/84/groups
Get the following JSON Response Payload:
[
{
"gid": 84,
"name": "_jabber",
"members": [
"84",
"Jabber XMPP Server",
"/var/empty",
"/usr/bin/false"
]
}
]
Why is 84 inside the members JSON array?
This is supposed to return all groups for the given user:
[
{
"gid": 29,
"name": "certusers",
"members": [
"root,_jabber,_postfix,_cyrus,_calendar,_dovecot"
]
},
{
"gid": 30,
"name": "_keytabusers",
"members": [
"_calendar,_jabber,_postfix"
]
}
]
Is there a way to map (e.g. link the two ArrayLists together or is there a different data structure that would help me do this) the User.uids with Group.gids?
This is all in-memory so please don't mention the use of ORM or JDBC.
My purpose it to print Json only with non empty objects. As in attached picture i have empty objects which i don't want to print them. It doesn't matter which library to choose either Gson or Jackson , etc'
Tried so far a lot of combination but in didn't worked
My data structure is :
Map<AWSRegion, List<SecurityGroupDiff>> listEntry...
public class SecurityGroupDiff {
#JsonInclude(Include.NON_EMPTY) ... // on all fields/objects
private String groupId;
private String groupName;
private String vpcId;
private String owner;
private String type;
private List<IPPermissionDiff> ipPermissionDiffs;
}
Tryid so far:
private static final ObjectMapper MAPPER = new ObjectMapper().
setSerializationInclusion(Include.NON_NULL).setSerializationInclusion(Include.NON_EMPTY).setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(listEntry)
the result is still the same ...
{
"CANADA" : [ { }, { }, { }, { }, {
"ipPermissionDiffs" : [ { }, { }, { }, { } ]
}, { }, { }, { } ],
"ASIA_SIDNEY" : [ {
"ipPermissionDiffs" : [ { }, { }, { }, { }, { } ]
}, { }, { }, { }, { }, { }, { }, {
"ipPermissionDiffs" : [ { }, { }, { }, { } ]
}, { } ],
"EU" : [ { }, { }, { }, { }, { }, { }, { }, { }, {
"ipPermissionDiffs" : [ { }, { }, { }, { }, { }, { }, { } ]
}, { } ]
}
thanks
{
"response_code": 200,
"debit": 3,
"position": "Train has reached Destination and late by 5 minutes",
"train": {
"number": "12046",
"name": "CDG NDLS SHTBDI"
},
"route": [
{
"no": 1,
"day": 0,
"station": {
"name": "CHANDIGARH",
"code": "CDG"
},
"has_arrived": false,
"has_departed": true,
"distance": 0,
"scharr": "Source",
"schdep": "12:00",
"actarr": "00:00",
"actdep": "12:00",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 0
},
{
"no": 2,
"day": 0,
"station": {
"name": "AMBALA CANT JN",
"code": "UMB"
},
"has_arrived": true,
"has_departed": true,
"distance": 67,
"scharr": "12:40",
"schdep": "12:42",
"actarr": "12:40",
"actdep": "12:42",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 0
},
{
"no": 3,
"day": 0,
"station": {
"name": "NEW DELHI",
"code": "NDLS"
},
"has_arrived": true,
"has_departed": false,
"distance": 265,
"scharr": "15:25",
"schdep": "Destination",
"actarr": "15:30",
"actdep": "00:00",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 5
}
]
}
public class TrainStatus {
public static int responseCode;
private int serialNo;
private String scheduleArrival;
private String actualArrival;
public static String station;
public static int debit;
private String statusOfArrival;
private boolean hasArrived;
private boolean hasDeparted;
private int latemin;
private String actualArrivalDate;
private String scheduleArrivalDate;
public static String position;
public String name;
public String getName()
{
return getName();
}
public void setName(String name)
{
this.name=name;
}
public boolean isHasArrived()
{
return hasArrived;
}
public void setHasArrived(boolean hasArrived)
{
this.hasArrived = hasArrived;
}
public boolean isHasDeparted()
{
return hasDeparted;
}
public void setHasDeparted(boolean hasDeparted)
{
this.hasDeparted = hasDeparted;
}
public int getLatemin()
{
return latemin;
}
public void setLatemin(int latemin)
{
this.latemin = latemin;
}
public void setSerialNo(int serialNo)
{
this.serialNo = serialNo;
}
public String getScheduleArrival()
{
return scheduleArrival;
}
public void setScheduleArrival(String scheduleArrival)
{
this.scheduleArrival = scheduleArrival;
}
public String getActualArrival()
{
return actualArrival;
}
public void setActualArrival(String actualArrival)
{
this.actualArrival = actualArrival;
}
public String getStation()
{
return station;
}
public void setStation(String station)
{
this.station = station;
}
public String getStatusOfArrival()
{
return statusOfArrival;
}
public void setStatusOfArrival(String statusOfArrival)
{
this.statusOfArrival = statusOfArrival;
}
public String getActualArrivalDate()
{
return actualArrivalDate;
}
public void setActualArrivalDate(String actualArrivalDate)
{
this.actualArrivalDate = actualArrivalDate;
}
public String getScheduleArrivalDate()
{
return scheduleArrivalDate;
}
public void setScheduleArrivalDate(String scheduleArrivalDate)
{
this.scheduleArrivalDate = scheduleArrivalDate;
}
}
public class TrainStatusParser {
public static List<TrainStatus> parseFeed(String content){
try
{
JSONObject jsonObject = new JSONObject(content);
List<TrainStatus> trainList = new ArrayList<>();
TrainStatus.responseCode = jsonObject.getInt("response_code");
TrainStatus.position = jsonObject.getString("position");
TrainStatus.debit=jsonObject.getInt("debit");
JSONArray route = jsonObject.getJSONArray("route");
for(int i=0;i<route.length();i++)
{
JSONObject routeObject = route.getJSONObject(i);
TrainStatus trainStatus = new TrainStatus();
if (jsonObject.has("station"))
{
JSONObject addressObject = jsonObject.getJSONObject("station");
trainStatus.name=addressObject.getString("name");
}
trainStatus.setSerialNo(routeObject.getInt("no"));
trainStatus.setScheduleArrival(routeObject.getString("scharr"));
trainStatus.setActualArrival(routeObject.getString("actarr"));
trainStatus.setStatusOfArrival(routeObject.getString("status"));
trainStatus.setHasArrived(routeObject.getBoolean("has_arrived"));
trainStatus.setHasDeparted(routeObject.getBoolean("has_departed"));
trainStatus.setLatemin(routeObject.getInt("latemin"));
trainStatus.setActualArrivalDate(routeObject.getString("actarr_date"));
trainStatus.setScheduleArrivalDate(routeObject.getString("scharr_date"));
trainList.add(trainStatus);
}
return trainList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Everything is correctly fetched except station name
Try this following code.
for(int i=0;i<route.length();i++) {
JSONObject routeObject = route.getJSONObject(i);
TrainStatus trainStatus = new TrainStatus();
JSONObject jsonObject_station = routeObject.getJSONObject("station");
String stationname = jsonObject_station.getString("name");
String code = jsonObject_station.getString("code");
Log.d("checkvalue", " " + stationname + " " + code);
trainStatus.setSerialNo(routeObject.getInt("no"));
trainStatus.setScheduleArrival(routeObject.getString("scharr"));
trainStatus.setActualArrival(routeObject.getString("actarr"));
trainStatus.setStatusOfArrival(routeObject.getString("status"));
trainStatus.setHasArrived(routeObject.getBoolean("has_arrived"));
trainStatus.setHasDeparted(routeObject.getBoolean("has_departed"));
trainStatus.setLatemin(routeObject.getInt("latemin"));
trainStatus.setActualArrivalDate(routeObject.getString("actarr_date"));
trainStatus.setScheduleArrivalDate(routeObject.getString("scharr_date"));
trainList.add(trainStatus);
}
Use a library from Google call GSON
In your posted code for parsing each route, you have this:
JSONObject routeObject = route.getJSONObject(i);
TrainStatus trainStatus = new TrainStatus();
if (jsonObject.has("station"))
{
JSONObject addressObject = jsonObject.getJSONObject("station");
trainStatus.name=addressObject.getString("name");
}
Looks like a typo here is causing your problems. You're calling jsonObject.has("station") when you should instead be calling routeObject.has("station"). Similarly, inside the if statement you should change jsonObject.getJSONObject("station") to routeObject.getJSONObject("station").