I'm quite new in JSON, I need a specific format of output JSON from Jackson API. Here is the output actually needed:
{
"0": {
"symbol": "B",
"count": 2,
"symbolIndex": [0, 0]
},
"1": {
"symbol": "B",
"count": 2,
"symbolIndex": [0, 0]
},
"2": {
"symbol": "B",
"count": 2,
"symbolIndex": [0, 0]
}
}
Consider that object names can vary (0,1,2,3,4,5....) and depends on the requirement and these can be only in incremental order. How can I use object to generate this JSON output in Java using Jackson API?
Update
So I have got the answer from Tom and the complete code is following:
MainClass.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MainClass {
public static void main(String[] args) {
SymbolCounts symbolCounts = new SymbolCounts();
symbolCounts.add("0", new MySymbol("A", 2, new int[]{1,1}));
symbolCounts.add("1", new MySymbol("B", 2, new int[]{1,1}));
symbolCounts.add("2", new MySymbol("C", 2, new int[]{1,1}));
String str = getJSONResponse(symbolCounts);
System.out.println(str);
}
protected static String getJSONResponse(SymbolCounts responseData) {
String jsonStringResponse = "";
try {
ObjectMapper mapper = new ObjectMapper();
jsonStringResponse = mapper.writeValueAsString(responseData);
} catch (JsonProcessingException jsonProcessingException) {
System.out.println(jsonStringResponse);
}
return jsonStringResponse;
}
}
SymbolCounts.java
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
#JsonInclude(NON_NULL)
#JsonIgnoreProperties(ignoreUnknown=true)
public class SymbolCounts {
#JsonProperty("symbolCounts")
private Map<String, MySymbol> symbolMap = new HashMap<String, MySymbol>();
#JsonAnySetter
public void add(String key, MySymbol value) {
symbolMap.put(key, value);
}
public Map<String, MySymbol> getSymbolMap() {
return symbolMap;
}
public void setSymbolMap(Map<String, MySymbol> symbolMap) {
this.symbolMap = symbolMap;
}
#Override
public String toString() {
return "SymbolCounts{" +
"symbolMap=" + symbolMap +
'}';
}
}
MySymbol.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Arrays;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
#JsonInclude(NON_NULL)
#JsonIgnoreProperties(ignoreUnknown=true)
public class MySymbol {
private String symbol;
private int count;
private int[] symbolIndex;
public MySymbol() {
}
public MySymbol(String symbol, int count, int[] symbolIndex) {
this.symbol = symbol;
this.count = count;
this.symbolIndex = symbolIndex;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int[] getSymbolIndex() {
return symbolIndex;
}
public void setSymbolIndex(int[] symbolIndex) {
this.symbolIndex = symbolIndex;
}
#Override
public String toString() {
return "LineID{" +
"symbol='" + symbol + '\'' +
", count=" + count +
", symbolIndex=" + Arrays.toString(symbolIndex) +
'}';
}
}
You could do this by using a map and the #JsonAnySetter.
Your higher level class would look like:
private Map<String, MySymbol> symbolMap;
#JsonAnySetter
public void add(String key, MySymbol value) {
symbolMap.put(key, value);
}
Your MySymbol class would just be:
private String symbol;
private Integer count;
private Integer[] symbolIndex;
Then your end result would be a map where the keys are your numeric values as Strings and the values are your symbol objects.
Related
I want to read a json file and store it into objects so that I can use it in my logic. After multiple attempts I was able to fetch the json into a Map. But I want the values to be stored in object and not a map.
Below is my code where I tried to fetch it and store in Currency object.
package com.springboot.currencyExchange;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import com.springboot.currencyExchange.model.*;
import com.springboot.currencyExchange.model.Currency;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.springboot.currencyExchange.service.MarketStrategyImpl;
#SpringBootApplication
public class CurrencyExchangeApplication {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
// SpringApplication.run(CurrencyExchangeApplication.class, args);
Object obj = new JSONParser().parse(new FileReader(
"*absolute path*\AvailableMarket.json"));
JSONObject jobj = (JSONObject) obj;
JSONArray ja = (JSONArray) jobj.get("currencies");
Iterator<Currency> itr1 = null;
Iterator<CurrentMarket> itr2 = ja.iterator();
while (itr2.hasNext()) {
itr1 = (Iterator<Currency>) (((List) itr2.next()).iterator());
while (itr1.hasNext()) {
Currency pair = itr1.next();
// System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
Below is my JSON file
{
"currencies": [
{
"currencyName": "Euro",
"price": 80
},
{
"currencyName": "Pound",
"price": 90
},
{
"currencyName": "USD",
"price": 75
}
],
"trades": [
{
"take": "Euro",
"give": "USD"
},
{
"take": "USD",
"give": "Pound"
}
]
}
Below are the POJO classes I created to store the JSON values:
package com.springboot.currencyExchange.model;
import java.util.List;
public class CurrentMarket {
public List<Currency> currency;
public List<Trade> trade;
public CurrentMarket() {
super();
}
public List<Currency> getCurrency() {
return currency;
}
public void setCurrency(List<Currency> currency) {
this.currency = currency;
}
public List<Trade> getTrade() {
return trade;
}
public CurrentMarket(List<Currency> currency, List<Trade> trade) {
super();
this.currency = currency;
this.trade = trade;
}
#Override
public String toString() {
return "CurrentMarket [currency=" + currency + ", trade=" + trade + "]";
}
public void setTrade(List<Trade> trade) {
this.trade = trade;
}
}
Currency.java
package com.springboot.currencyExchange.model;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Currency implements Serializable{
String currencyName;
Double price;
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Override
public String toString() {
return "Currency [currencyName=" + currencyName + ", price=" + price + "]";
}
public Currency(String currencyName, Double price) {
super();
this.currencyName = currencyName;
this.price = price;
}
}
Trade.java
package com.springboot.currencyExchange.model;
import java.util.ArrayList;
public class Trade {
ArrayList<String> take;
ArrayList<String> give;
public ArrayList<String> getTake() {
return take;
}
public Trade(ArrayList<String> take, ArrayList<String> give) {
super();
this.take = take;
this.give = give;
}
public void setTake(ArrayList<String> take) {
this.take = take;
}
public ArrayList<String> getGive() {
return give;
}
public void setGive(ArrayList<String> give) {
this.give = give;
}
}
I also tried the GSON approach but couldn't fetch it in desired format.
Below is the error message I get with current setup:
Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class java.util.List (org.json.simple.JSONObject is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
at com.springboot.currencyExchange.CurrencyExchangeApplication.main(CurrencyExchangeApplication.java:32)
I am not sure how else can I proceed. Any help would be appreciated.
You need to make a few changes at first.
As Abrar Ansari said, change the type of the variables from ArrayList to String in the Trade class. Also rename the currency and trade variables from the CurrencyMarket class to currencies and trades. Make all fields private in all model classes and make sure you have default constructors in all model classes. Then use Jackson's ObjectMapper to deserialize the json file into an object of type CurrentMarket:
ObjectMapper objectMapper = new ObjectMapper();
CurrentMarket currentMarket = objectMapper.readValue(new ClassPathResource("AvailableMarket.json").getFile(),
CurrentMarket.class);
This is my list which is coming in response now I have to add the objects belonging to particular itemIds using Java ,
[
{
"data": 210,
"dataValue":100,
"itemIds": "60e53dee7a814f0001de3538"
},
{
"data": 220,
"dataValue":120,
"itemIds": "60e53dee7a814f0001de3538"
},
{
"data": 110,
"dataValue":130,
"itemIds": "60e53dee7a814f0001de3539"
}
]
Ouput Required ->
[
{
"data": 430,
"Values":100,
"itemIds": "60e53dee7a814f0001de3538"
},
{
"data": 110,
"dataValue":130,
"itemIds": "60e53dee7a814f0001de3539"
}
]
You could do something like this
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListElement {
public static void main(String[] args) {
List<ListElement> elements = new ArrayList<ListElement>();
elements.add(new ListElement(210, 100, "60e53dee7a814f0001de3538"));
elements.add(new ListElement(220, 120, "60e53dee7a814f0001de3538"));
elements.add(new ListElement(110, 130, "60e53dee7a814f0001de3539"));
System.out.println(elements);
Map<String, List<ListElement>> elementsByItemId = elements.stream() //
.collect(Collectors.groupingBy(ListElement::getItemId)); //
elements = elementsByItemId.entrySet().stream() //
.map(entry -> new ListElement( //
entry.getValue().stream().collect(Collectors.summingInt(ListElement::getData)), //
entry.getValue().stream().collect(Collectors.summingInt(ListElement::getDataValue)), //
entry.getKey())) //
.collect(Collectors.toList());
System.out.println(elements);
}
int data;
int dataValue;
String itemId;
public ListElement(int data, int dataValue, String itemId) {
this.data = data;
this.dataValue = dataValue;
this.itemId = itemId;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public int getDataValue() {
return dataValue;
}
public void setDataValue(int dataValue) {
this.dataValue = dataValue;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
#Override
public String toString() {
return "ListElement [data=" + data + ", dataValue=" + dataValue + ", itemId=" + itemId + "]";
}
}
Here would be a not perfect example of how to do this. Maybe you can improve this solution to your liking. For simplicity it uses an inner class and exposed fields. I'm sure you will avoid doing this :)
It uses a custom aggregating operator and the reduce method of streams (see java stream reduce tutorial or java stream reduce doc)
private static BinaryOperator<Item> itemAggregator = (aggregatedResult, nextElement) -> {
aggregatedResult.data += nextElement.data;
aggregatedResult.dataValue += nextElement.dataValue;
return aggregatedResult;
};
public static void something(List<Item> initialItemList) {
Set<String> uniqueItemIds = initialItemList.stream()
.map(item -> item.itemId)
.collect(Collectors.toSet());
List<Item> resultList = uniqueItemIds.stream()
.map(itemId -> new Item(0, 0, itemId))
.collect(Collectors.toList());
resultList.forEach(
resultItem -> {
initialItemList.stream()
.filter(item -> item.itemId.equals(resultItem.itemId))
.reduce(resultItem, itemAggregator);
});
}
static class Item {
public int data;
public int dataValue;
public String itemId;
public Item(int data, int dataValue, String itemId) {
this.data = data;
this.dataValue = dataValue;
this.itemId = itemId;
}
}
But be aware, that using the reduce method can easily be done wrong (see avoid reduce if possible) and you have to check if it makes sense in your context.
Need to convert below JSON Object to String JAVA, getting stuck how to do with nested array. Below is the JSON object:
{
"url": "https://www.apple.com",
"defer_time": 5,
"email": true,
"mac_res": "1024x768",
"win_res": "1366X768",
"smart_scroll": true,
"layout": "portrait",
"configs": {
"windows 10": {
"chrome": [
"76",
"75"
],
"firefox": [
"67",
"66"
]
},
"macos mojave": {
"chrome": [
"76",
"75"
],
"firefox": [
"67",
"66"
]
}
}
}
Currently, I am using JSONObject and JSONArray to write the code, but not able to get it proper for nested array.
Any help will be appreciated, many thanks !!
this code will clear everything for you i hope. first to read json file you can open it with stream, them pass stream to JSONObject directly, because it has constructor for doing such trick, or append string from file to StringBuilder, then pass stringbuilder to string to JSONObject.
public static void main(String[] args) {
try(BufferedReader fileReader = new BufferedReader(new FileReader("test.json"))){
String line="";
StringBuilder stringBuilder = new StringBuilder();
while ((line = fileReader.readLine()) !=null){
stringBuilder.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
// to add single values yo your array.
// you can do something like this
JSONObject config = jsonObject.getJSONObject("configs");
JSONObject macos_mojave = config.getJSONObject("macos mojave");
JSONArray jsonArray = macos_mojave.getJSONArray("chrome"); // this way you will reach the array
jsonArray.put("77"); // then you can add them new values
jsonArray.put("78");
System.out.println(jsonArray.toList()); //will print your array content
} catch (IOException e){
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray(); // this is what you call single values, it is array
jsonArray.put(75);
jsonArray.put(76);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("Something", jsonArray);
}
you can write them back to file like this
//if you write them back to file you will see that 77 and 78 was added to chrome array (single values as you call them)
try(FileWriter fileWriter = new FileWriter("test.json")){
fileWriter.write(jsonObject.toString(5));
}catch (IOException ignore){
}
and after opening test.json file result will be next
{
"win_res": "1366X768",
"layout": "portrait",
"configs": {
"windows 10": {
"chrome": [
"76",
"75"
],
"firefox": [
"67",
"66"
]
},
"macos mojave": {
"chrome": [
"76",
"75",
"77",
"78"
],
"firefox": [
"67",
"66"
]
}
},
"smart_scroll": true,
"defer_time": 5,
"mac_res": "1024x768",
"url": "https://www.apple.com",
"email": true
}
as you see 77 and 78 was appended to "chrome" JSONArray. file will not track order because behind the scenes it is using HashMap.
Try to parse your string to the example Java object. Then call the toString method.
ObjectMapper mapper = newObjectMapper();
String jsonInString = "your string";
//JSON from String to Object
Example yourExample = mapper.readValue(jsonInString, Example.class);
yourExample.toString();
-----------------------------------com.example.Configs.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"windows 10",
"macos mojave"
})
public class Configs {
#JsonProperty("windows 10")
private Windows10 windows10;
#JsonProperty("macos mojave")
private MacosMojave macosMojave;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("windows 10")
public Windows10 getWindows10() {
return windows10;
}
#JsonProperty("windows 10")
public void setWindows10(Windows10 windows10) {
this.windows10 = windows10;
}
#JsonProperty("macos mojave")
public MacosMojave getMacosMojave() {
return macosMojave;
}
#JsonProperty("macos mojave")
public void setMacosMojave(MacosMojave macosMojave) {
this.macosMojave = macosMojave;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("windows10", windows10).append("macosMojave", macosMojave).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(windows10).append(additionalProperties).append(macosMojave).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Configs) == false) {
return false;
}
Configs rhs = ((Configs) other);
return new EqualsBuilder().append(windows10, rhs.windows10).append(additionalProperties, rhs.additionalProperties).append(macosMojave, rhs.macosMojave).isEquals();
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"url",
"defer_time",
"email",
"mac_res",
"win_res",
"smart_scroll",
"layout",
"configs"
})
public class Example {
#JsonProperty("url")
private String url;
#JsonProperty("defer_time")
private long deferTime;
#JsonProperty("email")
private boolean email;
#JsonProperty("mac_res")
private String macRes;
#JsonProperty("win_res")
private String winRes;
#JsonProperty("smart_scroll")
private boolean smartScroll;
#JsonProperty("layout")
private String layout;
#JsonProperty("configs")
private Configs configs;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("url")
public String getUrl() {
return url;
}
#JsonProperty("url")
public void setUrl(String url) {
this.url = url;
}
#JsonProperty("defer_time")
public long getDeferTime() {
return deferTime;
}
#JsonProperty("defer_time")
public void setDeferTime(long deferTime) {
this.deferTime = deferTime;
}
#JsonProperty("email")
public boolean isEmail() {
return email;
}
#JsonProperty("email")
public void setEmail(boolean email) {
this.email = email;
}
#JsonProperty("mac_res")
public String getMacRes() {
return macRes;
}
#JsonProperty("mac_res")
public void setMacRes(String macRes) {
this.macRes = macRes;
}
#JsonProperty("win_res")
public String getWinRes() {
return winRes;
}
#JsonProperty("win_res")
public void setWinRes(String winRes) {
this.winRes = winRes;
}
#JsonProperty("smart_scroll")
public boolean isSmartScroll() {
return smartScroll;
}
#JsonProperty("smart_scroll")
public void setSmartScroll(boolean smartScroll) {
this.smartScroll = smartScroll;
}
#JsonProperty("layout")
public String getLayout() {
return layout;
}
#JsonProperty("layout")
public void setLayout(String layout) {
this.layout = layout;
}
#JsonProperty("configs")
public Configs getConfigs() {
return configs;
}
#JsonProperty("configs")
public void setConfigs(Configs configs) {
this.configs = configs;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("url", url).append("deferTime", deferTime).append("email", email).append("macRes", macRes).append("winRes", winRes).append("smartScroll", smartScroll).append("layout", layout).append("configs", configs).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(configs).append(winRes).append(deferTime).append(email).append(additionalProperties).append(macRes).append(layout).append(smartScroll).append(url).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Example) == false) {
return false;
}
Example rhs = ((Example) other);
return new EqualsBuilder().append(configs, rhs.configs).append(winRes, rhs.winRes).append(deferTime, rhs.deferTime).append(email, rhs.email).append(additionalProperties, rhs.additionalProperties).append(macRes, rhs.macRes).append(layout, rhs.layout).append(smartScroll, rhs.smartScroll).append(url, rhs.url).isEquals();
}
}
-----------------------------------com.example.MacosMojave.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"chrome",
"firefox"
})
public class MacosMojave {
#JsonProperty("chrome")
private List<String> chrome = null;
#JsonProperty("firefox")
private List<String> firefox = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("chrome")
public List<String> getChrome() {
return chrome;
}
#JsonProperty("chrome")
public void setChrome(List<String> chrome) {
this.chrome = chrome;
}
#JsonProperty("firefox")
public List<String> getFirefox() {
return firefox;
}
#JsonProperty("firefox")
public void setFirefox(List<String> firefox) {
this.firefox = firefox;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("chrome", chrome).append("firefox", firefox).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(firefox).append(additionalProperties).append(chrome).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof MacosMojave) == false) {
return false;
}
MacosMojave rhs = ((MacosMojave) other);
return new EqualsBuilder().append(firefox, rhs.firefox).append(additionalProperties, rhs.additionalProperties).append(chrome, rhs.chrome).isEquals();
}
}
-----------------------------------com.example.Windows10.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"chrome",
"firefox"
})
public class Windows10 {
#JsonProperty("chrome")
private List<String> chrome = null;
#JsonProperty("firefox")
private List<String> firefox = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("chrome")
public List<String> getChrome() {
return chrome;
}
#JsonProperty("chrome")
public void setChrome(List<String> chrome) {
this.chrome = chrome;
}
#JsonProperty("firefox")
public List<String> getFirefox() {
return firefox;
}
#JsonProperty("firefox")
public void setFirefox(List<String> firefox) {
this.firefox = firefox;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("chrome", chrome).append("firefox", firefox).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(firefox).append(additionalProperties).append(chrome).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Windows10) == false) {
return false;
}
Windows10 rhs = ((Windows10) other);
return new EqualsBuilder().append(firefox, rhs.firefox).append(additionalProperties, rhs.additionalProperties).append(chrome, rhs.chrome).isEquals();
}
}
Here is how you could do it with BSON
import java.util.ArrayList;
import org.bson.Document;
Declare all the json objects and arrays you plan to use in your code.
Document root= new Document();
Document rootConfigs = new Document();
Document rootConfigsWindows10 = new Document();
ArrayList rootConfigsWindows10Chrome= new ArrayList();
ArrayList rootConfigsWindows10Firefox= new ArrayList();
Document rootConfigsMacosmojave = new Document();
ArrayList rootConfigsMacosmojaveChrome= new ArrayList();
ArrayList rootConfigsMacosmojaveFirefox= new ArrayList();
Assign out your strings and integers to the correct JSON documents.
root.append("url","https://www.apple.com");
root.append("defer_time",5);
root.append("email",true);
root.append("mac_res","1024x768");
root.append("win_res","1366X768");
root.append("smart_scroll",true);
root.append("layout","portrait");
rootConfigsWindows10Chrome.add("76");
rootConfigsWindows10Chrome.add("75");
rootConfigsWindows10Firefox.add("67");
rootConfigsWindows10Firefox.add("66");
rootConfigsMacosmojaveChrome.add("76");
rootConfigsMacosmojaveChrome.add("75");
rootConfigsMacosmojaveFirefox.add("67");
rootConfigsMacosmojaveFirefox.add("66");
Merge all the jsons together in the right order to form your nested JSON in the ROOT object
if (!rootConfigsWindows10Chrome.isEmpty()){
rootConfigsWindows10.append("chrome",rootConfigsWindows10Chrome);
}
if (!rootConfigsWindows10Firefox.isEmpty()){
rootConfigsWindows10.append("firefox",rootConfigsWindows10Firefox);
}
if (!rootConfigsWindows10.isEmpty()){
rootConfigs.append("windows 10",rootConfigsWindows10);
}
if (!rootConfigsMacosmojaveChrome.isEmpty()){
rootConfigsMacosmojave.append("chrome",rootConfigsMacosmojaveChrome);
}
if (!rootConfigsMacosmojaveFirefox.isEmpty()){
rootConfigsMacosmojave.append("firefox",rootConfigsMacosmojaveFirefox);
}
if (!rootConfigsMacosmojave.isEmpty()){
rootConfigs.append("macos mojave",rootConfigsMacosmojave);
}
if (!rootConfigs.isEmpty()){
root.append("configs",rootConfigs);
}
Output your JSON to see if it worked.
System.out.println(root.toJson());
After using http://www.jsonschema2pojo.org/ to create POJO class to convert JSON to Java Object I'm trying to get property of "distance" "inMeters" to compare them but I can't get them because it is List is there any way I can compare them
{
"originAddresses": [
"58 Oxford St, Fitzrovia, London W1D 1BH, UK"
],
"destinationAddresses": [
"109 Marylebone High St, Marylebone, London W1U 4RX, UK",
"143 Great Titchfield St, Fitzrovia, London W1W, UK",
"210 Great Portland St, Fitzrovia, London W1W 5BQ, UK",
"43-51 Great Titchfield St, Fitzrovia, London W1W 7PQ, UK"
],
"rows": [
{
"elements": [
{
"status": "OK",
"duration": {
"inSeconds": 457,
"humanReadable": "8 mins"
},
"distance": {
"inMeters": 1662,
"humanReadable": "1.7 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 383,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 1299,
"humanReadable": "1.3 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 376,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 1352,
"humanReadable": "1.4 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 366,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 932,
"humanReadable": "0.9 km"
}
}
]
}
]
}
This is my Main POJO Class in the compareTo class it require int but it show only List :
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class LocationGoogle implements Comparable<LocationGoogle> {
public LocationGoogle(String originAddress, String destinationAddress,Row
rows){
super();
this.destinationAddresses = destinationAddresses;
this.originAddresses = originAddresses;
this.rows= (List<Row>) rows;
}
#SerializedName("originAddresses")
#Expose
private List<String> originAddresses = null;
#SerializedName("destinationAddresses")
#Expose
private List<String> destinationAddresses = null;
#SerializedName("rows")
#Expose
private List<Row> rows = null;
public List<String> getOriginAddresses(){
return originAddresses;
}
public void setOriginAddresses(List<String> originAddresses){
this.originAddresses = originAddresses;
}
public List<String> getDestinationAddresses(){
return destinationAddresses;
}
public void setDestinationAddresses(List<String> destinationAddresses){
this.destinationAddresses = destinationAddresses;
}
public List<Row> getRows(){
return rows;
}
public void setRows(List<Row> rows){
this.rows = rows;
}
#Override
public int compareTo(LocationGoogle compareTime){
int compare =((LocationGoogle)compareTime).getRows();
return 0;
}
}
Is JSON to Java Object is good or bad way to convert JSON to java data. Should I keep doing this or find another way?
This is class Row :
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Row {
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
#Override
public String toString(){
return String.valueOf(elements);
}
}
This is Elements class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Element {
#SerializedName("status")
#Expose
private String status;
#SerializedName("duration")
#Expose
private Duration duration;
#SerializedName("distance")
#Expose
private Distance distance;
#Override
public String toString(){
return String.valueOf(distance);
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
}
This is Duration class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Duration {
#SerializedName("inSeconds")
#Expose
private Integer inSeconds;
#SerializedName("humanReadable")
#Expose
private String humanReadable;
public Integer getInSeconds() {
return inSeconds;
}
public void setInSeconds(Integer inSeconds) {
this.inSeconds = inSeconds;
}
public String getHumanReadable() {
return humanReadable;
}
public void setHumanReadable(String humanReadable) {
this.humanReadable = humanReadable;
}
#Override
public String toString (){
return String.valueOf(inSeconds);
}
}
This is Distance class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Distance implements Comparable{
#SerializedName("inMeters")
#Expose
private Integer inMeters;
#SerializedName("humanReadable")
#Expose
private String humanReadable;
public Integer getInMeters() {
return inMeters;
}
public void setInMeters(Integer inMeters) {
this.inMeters = inMeters;
}
public String getHumanReadable() {
return humanReadable;
}
public void setHumanReadable(String humanReadable) {
this.humanReadable = humanReadable;
}
#Override
public String toString(){
return String.valueOf(inMeters);
}
#Override
public int compareTo(Object o){
int compare = ((Distance)o).getInMeters();
return compare-this.inMeters;
}
}
The code i using to compare them:
#Override
public int compareTo(LocationGoogle compareTime){
String i= getRows()
int compare =((LocationGoogle)compareTime).getRows();
return 0;
}
After seeing required int but have List i confusing.
FileReader reader = new FileReader("Path to json file");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(reader);
System.out.println("json object = "+json.toString());
JSONArray result = (JSONArray) json.get("rows");
JSONObject result1 = (JSONObject)result.get(0);
JSONArray elements = (JSONArray) result1.get("elements");
JSONObject result2 = (JSONObject)elements.get(0);
JSONObject distance = (JSONObject)result2.get("distance");
JSONObject duration = (JSONObject)result2.get("duration");
Distance=(String)distance.get("inMeters");
use json_simple-1.0.2.jar file. It is step by step extraction.
I have the following JSON object and I want to deserialize it using Google's GSON library. Unfortunately I am unable to get the list correctly. GSON finds the first list entry but not the second.
This is the code I use for invoking GSON:
Mentions result = gson.fromJson(response, Mentions.class);
Here is my JSON File:
{
"mentions": [
{
"allEntities": [
{
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
],
"name": "Dylan",
"bestEntity": {
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
},
{
"name": "Duluth",
"bestEntity": {
"kbIdentifier": "YAGO:Duluth\\u002c_Minnesota",
"disambiguationScore": "0.63149"
}
}
]
}
And these are the plain old java objects I have created:
public class Mentions {
public List<Mention> mentions = new ArrayList<>();
}
public class Mention {
#SerializedName("bestEntity")
public BestEntity entity;
#SerializedName("name")
public String name;
}
public class BestEntity {
#SerializedName("kbIdentifier")
public String kbIdentifier;
#SerializedName("disambiguationScore")
public Double disambiguationScore;
}
I also tried directly deserializing the list, but it just gives me an error, saying that GSON expects the list to start at the beginning of the input.
Type datasetListType = new TypeToken<Collection<Mention>>() {
}.getType();
List<Mention> mentions = gson.fromJson(response, datasetListType);
Try this -
AllEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AllEntity {
#SerializedName("kbIdentifier")
#Expose
private String kbIdentifier;
#SerializedName("disambiguationScore")
#Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
#Override
public String toString() {
return "AllEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
BestEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BestEntity {
#SerializedName("kbIdentifier")
#Expose
private String kbIdentifier;
#SerializedName("disambiguationScore")
#Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
#Override
public String toString() {
return "BestEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
Mention.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mention {
#SerializedName("allEntities")
#Expose
private List<AllEntity> allEntities = new ArrayList<AllEntity>();
#SerializedName("name")
#Expose
private String name;
#SerializedName("bestEntity")
#Expose
private BestEntity bestEntity;
public List<AllEntity> getAllEntities() {
return allEntities;
}
public void setAllEntities(List<AllEntity> allEntities) {
this.allEntities = allEntities;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BestEntity getBestEntity() {
return bestEntity;
}
public void setBestEntity(BestEntity bestEntity) {
this.bestEntity = bestEntity;
}
#Override
public String toString() {
return "Mention [allEntities=" + allEntities + ", name=" + name
+ ", bestEntity=" + bestEntity + "]";
}
}
Main.java
import com.example.ElemntList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* #param args
*/
public static void main(String[] args) {
String s = "{\"mentions\":[{\"allEntities\":[{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}],\"name\":\"Dylan\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}},{\"name\":\"Duluth\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Duluth\\u002c_Minnesota\",\"disambiguationScore\":\"0.63149\"}}]}";
ElemntList info = gson.fromJson(s, ElemntList.class);
System.out.println(info);
}
}
Result is -
ElemntList [mentions=[Mention [allEntities=[AllEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], name=Dylan, bestEntity=BestEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], Mention [allEntities=[], name=Duluth, bestEntity=BestEntity [kbIdentifier=YAGO:Duluth,_Minnesota, disambiguationScore=0.63149]]]]
Shouldn't you use the class you've created ? I.E Mentions
gson.fromJson(response, Mentions.class);
And if I were you, I would map all fields just in case you may need it, you're missing allEntities.