I'm having some trouble with how to map a JSON correctly. I have to save this incoming JSON in my DB:
{
"request": {
"Target": "Affiliate_Offer",
"Format": "json",
"Service": "HasOffers",
"Version": "2",
"api_key": "3225235c56334584b1360d",
"Method": "findAll",
"contain": [
"Country"
]
},
"response": {
"status": 1,
"httpStatus": 200,
"data": {
"18292": {
"Offer": {
"id": "18292",
"name": "247 Profit Formula",
"approval_status": "approved"
},
"Country": {
"US": {
"id": "840",
"code": "US",
"name": "United States",
"regions": {
"4": {
"id": "4",
"country_code": "US",
"country_code_3c": "USA",
"code": "AR",
"name": "Arkansas"
},
"5": {
"id": "5",
"country_code": "US",
"country_code_3c": "USA",
"code": "CA",
"name": "California"
},
"10": {
"id": "10",
"country_code": "US",
"country_code_3c": "USA",
"code": "FL",
"name": "Florida"
}
},
"CA": {
"id": "124",
"code": "CA",
"name": "Canada",
"regions": []
}
}
},
"17823": {
"Offer": {
"id": "17823",
"name": "American Career Guide",
"approval_status": null
},
"Country": {
"Country": {
"US": {
"id": "840",
"code": "US",
"name": "United States",
"regions": []
},
"UK": {
"id": "826",
"code": "UK",
"name": "United Kingdom",
"regions": []
},
"AU": {
"id": "36",
"code": "AU",
"name": "Australia",
"regions": []
},
"CA": {
"id": "124",
"code": "CA",
"name": "Canada",
"regions": []
},
"NZ": {
"id": "554",
"code": "NZ",
"name": "New Zealand",
"regions": []
}
}
}
},
The Offer structure is already mapped, but I'm having some trouble with the Country.
The OfferMapper:
#Data
#AllArgsConstructor
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class OfferMapper {
OfferRequest request;
OfferResponse response;
}
The OfferResponse:
#Getter #Setter
#JsonIgnoreProperties(ignoreUnknown = true)
public class OfferResponse {
#JsonProperty("status")
private int status;
#JsonProperty("httpStatus")
private int httpStatus;
#JsonProperty("data")
private Map<String, OfferData> data;
}
Here is the structure that I'm having trouble. The OfferData:
#Getter #Setter
#JsonIgnoreProperties(ignoreUnknown = true)
public class OfferData {
#JsonProperty("Offer")
Offer offer;
#JsonProperty("Country")
Country country;
}
I tried to put in a map like this Map<Country, String> countries; and List<Map<Country, String>> countries; no luck so far to arrange this part with a POJO:
"Country": {
"US": {
"id": "840",
"code": "US",
"name": "United States",
"regions": []
}
}
"Country": {
"US": {
"id": "840",
"code": "US",
"name": "United States",
"regions": []
}
}
It is equivalent to receiving an object of Country that has an object of US.
Structure of US
public class US
{
private String id;
private String code;
private String name;
private List<String> regions; //if regions is gonna be list of strings
//getters and setters
}
Your Json Country is having letter C as capital hence it might be the issue that Jackson is not recognizing it. Check Java Naming conventions and other docs for more information.
class Data {
private String id;
private String code;
private String name;
private List<String> regions;
}
class CountryData {
public Map<String, Data> getCountry() {
return Country;
}
public void setCountry(Map<String, Data> Country) {
Country = Country;
}
//To resolve the error you need to add the below tag and define your class accordingly.
#JsonProperty("Country")
private Map<String, Data> Country;
}
public class POJO {
public static void main(String[] args) throws JsonProcessingException {
String countryjson = "{\n" +
" \"Country\": {\n" +
" \"US\": {\n" +
" \"id\": \"840\",\n" +
" \"code\": \"US\",\n" +
" \"name\": \"United States\",\n" +
" \"regions\": []\n" +
" },\n" +
" \"UK\": {\n" +
" \"id\": \"826\",\n" +
" \"code\": \"UK\",\n" +
" \"name\": \"United Kingdom\",\n" +
" \"regions\": []\n" +
" },\n" +
" \"AU\": {\n" +
" \"id\": \"36\",\n" +
" \"code\": \"AU\",\n" +
" \"name\": \"Australia\",\n" +
" \"regions\": []\n" +
" },\n" +
" \"CA\": {\n" +
" \"id\": \"124\",\n" +
" \"code\": \"CA\",\n" +
" \"name\": \"Canada\",\n" +
" \"regions\": []\n" +
" },\n" +
" \"NZ\": {\n" +
" \"id\": \"554\",\n" +
" \"code\": \"NZ\",\n" +
" \"name\": \"New Zealand\",\n" +
" \"regions\": []\n" +
" }\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
CountryData country = objectMapper.readValue(countryjson, CountryData.class);
System.out.println(country.toString());
}
}
It should work, Add #JsonProperty Tag in you POJO definition.
Related
I have the following method that when receiving an xml in a String converts it to objects of type CitiMarketSSAEvent
public CitiMarketSSAEvent convertXmlToObject(String xml){
CitiMarketSSAEvent citiMarket = null;
JAXBContext jaxbContext = JAXBContext.newInstance(CitiMarketSSAEvent.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xml);
citiMarket = (CitiMarketSSAEvent) unmarshaller.unmarshal(reader);
return citiMarket;
}
and then I have the following method that converts the objects of that class into a json
public String convertObjectToJson(CitiMarketSSAEvent citiMarketObject) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.disableHtmlEscaping();
Gson gson = gsonBuilder.create();
return gson.toJson(citiMarketObject, CitiMarketSSAEvent.class);
}
and it paints the json as follows
{
"header":{
"name": "transactionCount",
"version": "2.0",
"code": "1530",
"country": "MX",
"domain": "counts",
"time": "2018-10-11 11:20:34.323 GMT",
},
"body":{
"INPUNT": "I",
"MESSAGE_01": "RSTW",
"MESSAGE_02": "MNXTYP",
"MESSAGE_03": "RSTWERDCV",
"SEND_TIME": "20-NOV-2011 04:53:04 p.m.",
"RCV_ID": "ABGRCV",
"FORMAT0_MONTO": "200,000,300.00",
"FORMATO_MONEDA": "USD",
"CONTROL_01": "MSG1RCVSND",
"CONTROL_02": "MSG2RCVSND",
"CONTROL_03": "MSG3RCVSND",
}
}
but I want to add the "event" key to the json in such a way that I get something like this:
{
"event":{
"header":{
"name": "transactionCount",
"version": "2.0",
"code": "1530",
"country": "MX",
"domain": "counts",
"time": "2018-10-11 11:20:34.323 GMT",
},
"body":{
"INPUNT": "I",
"MESSAGE_01": "RSTW",
"MESSAGE_02": "MNXTYP",
"MESSAGE_03": "RSTWERDCV",
"SEND_TIME": "20-NOV-2011 04:53:04 p.m.",
"RCV_ID": "ABGRCV",
"FORMAT0_MONTO": "200,000,300.00",
"FORMATO_MONEDA": "USD",
"CONTROL_01": "MSG1RCVSND",
"CONTROL_02": "MSG2RCVSND",
"CONTROL_03": "MSG3RCVSND",
}
}
}
and then I modified my method as follows using JSONObject
public String convertObjectToJson(CitiMarketSSAEvent citiMarketObject) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.disableHtmlEscaping();
JSONObject jsonObj = new JSONObject();
jsonObj.put("event",citiMarketObject);
Gson gson = gsonBuilder.create();
return gson.toJson(jsonObj, JSONObject.class);
}
and it throws me the json but the key "nameValuePairs" was added, how can it be removed? Or how else can I do it to just add the "event" key?
{
"nameValuePairs":{
"event":{
"header":{
"name": "transactionCount",
"version": "2.0",
"code": "1530",
"country": "MX",
"domain": "counts",
"time": "2018-10-11 11:20:34.323 GMT",
},
"body":{
"INPUNT": "I",
"MESSAGE_01": "RSTW",
"MESSAGE_02": "MNXTYP",
"MESSAGE_03": "RSTWERDCV",
"SEND_TIME": "20-NOV-2011 04:53:04 p.m.",
"RCV_ID": "ABGRCV",
"FORMAT0_MONTO": "200,000,300.00",
"FORMATO_MONEDA": "USD",
"CONTROL_01": "MSG1RCVSND",
"CONTROL_02": "MSG2RCVSND",
"CONTROL_03": "MSG3RCVSND",
}
}
}
}
Try this code, it is supposed to do what you need.
package com;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
String json = "{\n" +
" \"header\":{\n" +
" \"name\": \"transactionCount\",\n" +
" \"version\": \"2.0\",\n" +
" \"code\": \"1530\",\n" +
" \"country\": \"MX\",\n" +
" \"domain\": \"counts\",\n" +
" \"time\": \"2018-10-11 11:20:34.323 GMT\"\n" +
" },\n" +
" \"body\":{\n" +
" \"INPUNT\": \"I\",\n" +
" \"MESSAGE_01\": \"RSTW\",\n" +
" \"MESSAGE_02\": \"MNXTYP\",\n" +
" \"MESSAGE_03\": \"RSTWERDCV\",\n" +
" \"SEND_TIME\": \"20-NOV-2011 04:53:04 p.m.\",\n" +
" \"RCV_ID\": \"ABGRCV\",\n" +
" \"FORMAT0_MONTO\": \"200,000,300.00\",\n" +
" \"FORMATO_MONEDA\": \"USD\",\n" +
" \"CONTROL_01\": \"MSG1RCVSND\",\n" +
" \"CONTROL_02\": \"MSG2RCVSND\",\n" +
" \"CONTROL_03\": \"MSG3RCVSND\"\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
LinkedHashMap hashMap = objectMapper.readValue(json, LinkedHashMap.class);
Event event = new Event(hashMap);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
}
public static class Event {
#JsonProperty("event")
private LinkedHashMap event;
public Event(LinkedHashMap event){
this.event = event;
}
}
}
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.
All,
I have following JSON response after request get list of users. I want to pull just only one user's id using userName. For example if i want id of userName Test1, how to do that? Any help will be appreciated.
{
"displayLength": "4",
"iTotal": "20",
"users": [
{
"id": "2",
"userName": "Test1",
"Group": { id:1
name:"Test-Admin"
}
},
{
"id": "17",
"userName": "Test2",
"Group": { id:1
name:"Test-Admin"
}
},
{
"id": "32",
"userName": "Test3",
"Group": { id:1
name:"Test-Admin"
}
},
{
"id": "35",
"userName": "Test4",
"Group": { id:1
name:"Test-Admin"
}
}
]
}
Thanks,
See if this below code helps. Just pass user name to userName variable and let the code find the userId for you.
JSONObject json = new JSONObject(" {\n" + " \"displayLength\": \"4\",\n"
+ " \"iTotal\": \"20\",\n" + " \"users\": [\n" + " {\n"
+ " \"id\": \"2\",\n" + " \"userName\": \"Test1\",\n"
+ " \"Group\": { id:1,\n" + " name:\"Test-Admin\"\n"
+ " }\n" + " },\n" + " {\n" + " \"id\": \"17\",\n"
+ " \"userName\": \"Test2\",\n" + " \"Group\": { id:1,\n"
+ " name:\"Test-Admin\"\n" + " }\n" + " },\n"
+ " {\n" + " \"id\": \"32\",\n" + " \"userName\": \"Test3\",\n"
+ " \"Group\": { id:1,\n" + " name:\"Test-Admin\"\n"
+ " }\n" + " },\n" + " {\n" + " \"id\": \"35\",\n"
+ " \"userName\": \"Test4\",\n" + " \"Group\": { id:1,\n"
+ " name:\"Test-Admin\"\n" + " }\n" + " } \n"
+ "\n" + " ]\n" + " }");
JSONArray array = json.getJSONArray("users");
String userName = "Test1";
Integer userId = null;
for (int i = 0; i < array.length() && userId == null; i++) {
JSONObject jsonIn = (JSONObject) array.get(i);
if (jsonIn.optString("userName").equals(userName)) {
userId = jsonIn.optInt("id");
}
}
System.out.println("User ID for User Name '" + userName + "' is : " + userId);
I recomend use http-request built on apache http api. You must create class ResponseData to parse response.
private static final HttpRequest<ResponseData> HTTP_REQUEST =
HttpRequestBuilder.createGet(yourUri, ResponseData.class).build();
public void test() {
HTTP_REQUEST.execute().ifHasContent(responseData -> {
Optional<User> foundedUser = responseData.getUsers()
.stream()
.filter(user -> "Test1".equals(user.getUserName()))
.findFirst();
foundedUser.ifPresent(user -> System.out.println(user.getId()));
});
}
class ResponseData {
private int displayLength;
private int iTotal;
private List<User> users;
public int getDisplayLength() {
return displayLength;
}
public void setDisplayLength(int displayLength) {
this.displayLength = displayLength;
}
public int getiTotal() {
return iTotal;
}
public void setiTotal(int iTotal) {
this.iTotal = iTotal;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
class User {
private int id;
private String userName;
private Group Group;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Group getGroup() {
return Group;
}
public void setGroup(Group group) {
Group = group;
}
}
class Group {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Note: Your json is incorrect. See Corrected:
{
"displayLength": "4",
"iTotal": "20",
"users": [
{
"id": "2",
"userName": "Test1",
"Group": {
"id": 1,
"name": "Test-Admin"
}
},
{
"id": "17",
"userName": "Test2",
"Group": {
"id": 1,
"name": "Test-Admin"
}
},
{
"id": "32",
"userName": "Test3",
"Group": {
"id": 1,
"name": "Test-Admin"
}
},
{
"id": "35",
"userName": "Test4",
"Group": {
"id": 1,
"name": "Test-Admin"
}
}
]
}
jsonObj.getJsonArray("users") and then convert the array to list. Now use Java 8 Stream and Filter api's to extract the desired output.
I have following json data:-
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
Method to assert json:-
public void assertJsonvalue (String description, String jsonString,
String path, Object expectedValue) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> jsonMap = null;
try {
jsonMap = objectMapper.readValue(jsonString,
new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) {
fail("Could not parse json from string:" + jsonString);
}
Object actualValue = null;
try {
actualValue = PropertyUtils.getProperty(jsonMap, path);
System.out.println("actualValue" + actualValue);
} catch (IllegalAccessException e) {
// error here
}
assertEquals(description, expectedValue, actualValue);
}
When I try to get json value from by using the following, Its works well.
assertJsonValue("bicycle color", json, "store.bicycle.color", "red");
I want to get array value from json such as details of 1st book.
I have tried the following, that doesn't help me out.
json paths are as follows:-
"store.book[0]"
"store.book.[0]"
"store.book.category"
How Can I do this ?
According to this answer, you should be able to get the mentioned properties like this:
assertJsonValue("...", json, "store.(book)[0].category", "reference");
Edit:
Which version of jackson and beanutils are you using? I've modified your method a bit and made a simple test case, using beanutils 1.9.2 and jackson 2.6.5 tests seem to pass:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class TestJson {
private static final String JSON = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}";
#Test
public void testJson() {
assertTrue(assertJsonValue(JSON, "store.(book)[0].category", "reference"));
assertTrue(assertJsonValue(JSON, "store.(book)[0].author", "Nigel Rees"));
assertTrue(assertJsonValue(JSON, "store.(book)[0].title", "Sayings of the Century"));
assertTrue(assertJsonValue(JSON, "store.(book)[0].price", 8.95));
}
public boolean assertJsonValue(String jsonString,
String path,
Object expectedValue) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Object actual = PropertyUtils
.getProperty(objectMapper.readValue(jsonString, Object.class), path);
if (actual.equals(expectedValue)) {
return true;
}
} catch (IOException | ReflectiveOperationException e) {
// handle error
}
return false;
}
}
How can I retrieve value from this JSON in android?
I want to create an ArrayList. I've tried JSONObject to access the value. But It need to create object for every city. I want to access all city using a loop inside it like as follows.
{
"City A": {
"Position": {
"Longitude": 9.96233,
"Latitude": 49.80404
}
},
"City B": {
"Position": {
"Longitude": 6.11499,
"Latitude": 50.76891
}
},
"City C": {
"Position": {
"Longitude": 6.80592,
"Latitude": 51.53548
}
},
"City D": {
"Position": {
"Longitude": 9.50523,
"Latitude": 51.31991
}
},
"City E": {
"Position": {
"Longitude": 9.66089,
"Latitude": 48.70158
}
},
"City F": {
"Position": {
"Longitude": 9.93368,
"Latitude": 53.55608
}
},
"City G": {
"Position": {
"Longitude": 11.56122,
"Latitude": 48.14496
}
},
"City H": {
"Position": {
"Longitude": 13.34253,
"Latitude": 52.5319
}
},
"City I": {
"Position": {
"Longitude": 6.11327,
"Latitude": 50.77715
}
},
"City J": {
"Position": {
"Longitude": 13.36671,
"Latitude": 52.54344
}
}
}
How can I manage this when I want the same?
You can do this:
City.java (model class)
public class City implements Comparable {
private String name; // The name of the city
private double latitude; // its latitude
private double longitude; // its longitude
public City(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
#Override
public String toString() {
return name + ": " + latitude + " - " + longitude;
}
#Override
public int compareTo(Object c) {
City city = (City) c;
return name.compareTo(city.name);
}
}
App.java:
public class App {
public static void main(String[] args) {
// Your JSON string
String jsonString = "{\"City A\":{\"Position\":{\"Longitude\":9.96233,\"Latitude\":49.80404}},\"City B\":{\"Position\":{\"Longitude\":6.11499,\"Latitude\":50.76891}},\"City C\":{\"Position\":{\"Longitude\":6.80592,\"Latitude\":51.53548}},\"City D\":{\"Position\":{\"Longitude\":9.50523,\"Latitude\":51.31991}},\"City E\":{\"Position\":{\"Longitude\":9.66089,\"Latitude\":48.70158}},\"City F\":{\"Position\":{\"Longitude\":9.93368,\"Latitude\":53.55608}},\"City G\":{\"Position\":{\"Longitude\":11.56122,\"Latitude\":48.14496}},\"City H\":{\"Position\":{\"Longitude\":13.34253,\"Latitude\":52.5319}},\"City I\":{\"Position\":{\"Longitude\":6.11327,\"Latitude\":50.77715}},\"City J\":{\"Position\":{\"Longitude\":13.36671,\"Latitude\":52.54344}}}";
JSONObject jsonObj = new JSONObject(jsonString);
List<City> cities = new ArrayList<>(); // The arraylist that will hold the cities
// A JSON array with the the names of all the cities
JSONArray cityNames = jsonObj.names();
for(int i = 0; i < jsonObj.length(); i++) {
String cityName = cityNames.getString(i);
JSONObject jsonCity = jsonObj.getJSONObject(cityName);
JSONObject jsonPosition = jsonCity.getJSONObject("Position");
cities.add(new City(cityName, jsonPosition.getDouble("Latitude"), jsonPosition.getDouble("Longitude")));
}
Collections.sort(cities); // Sort the cities' arraylist by city name
cities.forEach(System.out::println); // Print the cities
}
}
Output:
City A: 49.80404 - 9.96233
City B: 50.76891 - 6.11499
City C: 51.53548 - 6.80592
City D: 51.31991 - 9.50523
City E: 48.70158 - 9.66089
City F: 53.55608 - 9.93368
City G: 48.14496 - 11.56122
City H: 52.5319 - 13.34253
City I: 50.77715 - 6.11327
City J: 52.54344 - 13.36671
You can use Google gson to convert string to Java object.
TO get Data with for loop you should have JSONArray.
This is response you should use.
Then using this code you can apply for loop and List or ArrayList to save data.
[{
"city_name": "City A",
"Position": {
"Longitude": 9.96233,
"Latitude": 49.80404
}
}, {
"city_name": "City B",
"Position": {
"Longitude": 6.11499,
"Latitude": 50.76891
}
}, {
"city_name": "City C",
"Position": {
"Longitude": 6.80592,
"Latitude": 51.53548
}
}, {
"city_name": "City D",
"Position": {
"Longitude": 9.50523,
"Latitude": 51.31991
}
}, {
"city_name": "City E",
"Position": {
"Longitude": 9.66089,
"Latitude": 48.70158
}
}, {
"city_name": "City F",
"Position": {
"Longitude": 9.93368,
"Latitude": 53.55608
}
}, {
"city_name": "City G",
"Position": {
"Longitude": 11.56122,
"Latitude": 48.14496
}
}, {
"city_name": "City H",
"Position": {
"Longitude": 13.34253,
"Latitude": 52.5319
}
}, {
"city_name": "City I",
"Position": {
"Longitude": 6.11327,
"Latitude": 50.77715
}
}, {
"city_name": "City J",
"Position": {
"Longitude": 13.36671,
"Latitude": 52.54344
}
}]
then Java code as:
JSONArray json_array= new JSONArray(responseString);
for(int i= 0; i<json_array.length(); i++){
JSONObject json_object = json_array.get(i);
String cityname=json_object.getString("city_name");
JSONObject json_object_position = json_object.getJSONObject("Position");
long longitude=json_object_position.getString("Longitude");
long latitude=json_object_position.getString("Latitude");
// Save the data in List you want.
}
You can use names() method of JSONObject.
Try this :
JSONObject jsonObject = new JSONObject(yourjsonString);
JSONArray jarray = jsonObject.names();
for(int i= 0; i<jarray.length(); i++){
String name = jarray.getString(i);
}