What is the quickest way to parse this json array into a list?
[
["FundRequest"],
["nOS"],
["NEX"],
["DREP"],
["ChromaWay"],
["Jura"],
["Origo"],
["Phantasma"],
["NuCypher"],
["Oasis Labs"]
]
Its being generated from the following code:
private void getNames(String spreadsheetUrl) {
JSONObject json = readJsonFromUrl(spreadsheetUrl);
String result = json.get("values").toString();
log.debug("Found: {}", result);
}
The output is from the following json response:
{
"range": "Frontpage!E6:E15",
"majorDimension": "ROWS",
"values": [
[
"FundRequest"
],
[
"nOS"
],
[
"NEX"
],
[
"DREP"
],
[
"ChromaWay"
],
[
"Jura"
],
[
"Origo"
],
[
"Phantasma"
],
[
"NuCypher"
],
[
"Oasis Labs"
]
]
}
You could use a library like GSON:
Install it with maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
EDIT:
If you're trying to parse this:
{
"range": "Frontpage!E6:E15",
"majorDimension": "ROWS",
"values": [
[
"FundRequest"
],
[
"nOS"
],...
as a java object then create a wrapper class for your json entity:
public class Wrapper {
private String range;
private String majorDimension;
private List<?> values;
/**
* #return the range
*/
public String getRange() {
return range;
}
/**
* #return the values
*/
public List<?> getValues() {
return values;
}
/**
* #param values the values to set
*/
public void setValues(List<?> values) {
this.values = values;
}
/**
* #return the majorDimension
*/
public String getMajorDimension() {
return majorDimension;
}
/**
* #param majorDimension the majorDimension to set
*/
public void setMajorDimension(String majorDimension) {
this.majorDimension = majorDimension;
}
/**
* #param range the range to set
*/
public void setRange(String range) {
this.range = range;
}
}
Then using GSON you can parse a Json string into a wrapper object:
Gson gson = new GsonBuilder().create();
Wrapper w = gson.fromJson(jsonString, Wrapper.class);
Check this: http://www.javacreed.com/simple-gson-example/
EDIT:
If you're trying to parse this:
[
["FundRequest"],
["nOS"],
["NEX"],
["DREP"],
["ChromaWay"],
["Jura"],
["Origo"],
["Phantasma"],
["NuCypher"],
["Oasis Labs"]
]
As an array of arrays, then using gson you can do:
List<?> arr = gson.fromJson("[[\"FundRequest\"],[\"nOS\"],...]", List.class);
System.out.println(arr);
The println shall print:
[[FundRequest], [nOS], ...]
The json array of arrays shall be parsed as a list of lists
Hope this helps
Related
When I call my API with a request body I deserialize it with the variable name in my POJO. I modify the same list and return back but it duplicates the list
#JsonSerialize
#JsonIgnoreProperties(ignoreUnknown = true)
public class UASchema {
#JsonProperty("metric_id")
private ArrayList<String> fMetricId;
#JsonProperty("schema")
private ArrayList<String> fSchema;
#JsonProperty("hash")
private String fHash;
...
...
//getter and setters
}
Request body is
{
"data" : [
{
"metric_id": ["k1", "ak2", "d90"],
"schema": ["s1", "s2"]
},
{
"metric_id": ["k21", "k22"],
"schema": ["a11", "s22"]
}
]
}
Response I get is (added hash)
{
"result": [
{
"fmetricId": [
"k1",
"ak2",
"d90"
],
"fschema": [
"s1",
"s2"
],
"metric_id": [
"k1",
"ak2",
"d90"
],
"schema": [
"s1",
"s2"
],
"hash": "389abc9093442cfd2aee1f20807ba467"
},
{
"fmetricId": [
"k21",
"k22"
],
"fschema": [
"a11",
"s22"
],
"metric_id": [
"k21",
"k22"
],
"schema": [
"a11",
"s22"
],
"hash": "5f366dde65b69fa679f95a81f3115b7f"
}
]
}
It duplicates the list and not correctly serializing it. I want the response to just have the same list as request body and I added hash back.
It looks like your algorithm duplicates entries or you manually generated getters and setters which duplicate output. By default Jackson does not add extra entries. See below example how you can do that, I generated getters and setters in IDE. f-fieldName pattern for fields is outdated and you should use regular names. See, for example, Google's Java Guide:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.File;
import java.util.List;
import java.util.UUID;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Root root = mapper.readValue(jsonFile, Root.class);
root.getData().forEach(s -> s.setfHash(UUID.randomUUID().toString()));
System.out.println(mapper.writeValueAsString(root));
}
}
class Root {
private List<UASchema> data;
public List<UASchema> getData() {
return data;
}
public void setData(List<UASchema> data) {
this.data = data;
}
#Override
public String toString() {
return "Root{" +
"data=" + data +
'}';
}
}
class UASchema {
#JsonProperty("metric_id")
private List<String> fMetricId;
#JsonProperty("schema")
private List<String> fSchema;
#JsonProperty("hash")
private String fHash;
public List<String> getfMetricId() {
return fMetricId;
}
public void setfMetricId(List<String> fMetricId) {
this.fMetricId = fMetricId;
}
public List<String> getfSchema() {
return fSchema;
}
public void setfSchema(List<String> fSchema) {
this.fSchema = fSchema;
}
public String getfHash() {
return fHash;
}
public void setfHash(String fHash) {
this.fHash = fHash;
}
#Override
public String toString() {
return "UASchema{" +
"fMetricId=" + fMetricId +
", fSchema=" + fSchema +
", fHash='" + fHash + '\'' +
'}';
}
}
Above code prints:
{
"data" : [ {
"metric_id" : [ "k1", "ak2", "d90" ],
"schema" : [ "s1", "s2" ],
"hash" : "80dcf06d-1d83-463c-afb8-edef8efdc71f"
}, {
"metric_id" : [ "k21", "k22" ],
"schema" : [ "a11", "s22" ],
"hash" : "a83d7981-4b80-4318-a632-f3c91d14379b"
} ]
}
Im using jsonProperty annonation to map json values to variables in pojo object.
{
"valueSet": [
{
"name": "Type_int",
"value": 123
},
{
"name": "Type_String",
"value": "ABC"
}
]
}
For this above json, I am using Object class object to capture "value" attribute value.
like
#JsonProperty("value")
private Object value;
This working fine to capture both "Integer" and "String" value.
But for below scenario
{
"valueSet": [
{
"name": "Type_int",
"value": 123
},
{
"name": "Type_String",
"value": "ABC"
},
{
"name": "Type_array",
"value": [
{
"x": 0,
"y": 0
},
{
"x": 10,
"y": 10
},
{
"x": 20,
"y": 20
}
]
}
]
}
There are three different data types for "value" attribute.I cannot use Object to capture value. So, is there any way to capture all values in "value" attribute.
Just trying my luck, with below code,
The Value class
public class Value {
#JsonProperty("name")
private String name;
#JsonProperty("value")
private Object value;
#JsonProperty("value")
private ValueObject valueObject;
//setters and getters
}
ValueSet class
public class ValueSet {
#JsonProperty("valueSet")
private List<Value> l;
//setters & getters
}
ValueObject class
public class ValueObject {
#JsonProperty("x")
private int x;
#JsonProperty("y")
private int y;
//setters & getters
}
And the test method
#Test
public void test() {
String input = "{\"valueSet\":[{\"name\":\"Type_int\",\"value\":123},{\"name\":\"Type_String\",\"value\":\"ABC\"},{\"name\":\"Type_array\",\"value\":[{\"x\":0,\"y\":0},{\"x\":10,\"y\":10},{\"x\":20,\"y\":20}]}]}";
//String input = "{\"valueSet\":[{\"name\":\"Type_int\",\"value\":123},{\"name\":\"Type_String\",\"value\":\"ABC\"}]}";
ObjectMapper mapper = new ObjectMapper();
try {
ValueSet v = mapper.readValue(input, ValueSet.class);
System.out.println(v);
} catch (IOException e) {
e.printStackTrace();
}
}
Output, in reverse order.
ValueSet [l=[Value [name=Type_int, value=123], Value [name=Type_String, value=ABC]]]
ValueSet [l=[Value [name=Type_int, value=123], Value [name=Type_String, value=ABC], Value [name=Type_array, value=[{x=0, y=0}, {x=10, y=10}, {x=20, y=20}]]]]
Add toString() methods to see output in log or console. And somehow this works for me. Not sure if it would work for you.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("valueSet");
for(int i=0; i<jsonArray.length(); i++) {
System.out.println(jsonArray.optJSONObject(i).get("value").toString());
}
I have this class:
#Getter
#Setter
IntestatarioPrivacySospensiva {
private IntestatarioInput intestatario;
private List<DatiPrivacySospensiva> datiPrivacy;
private String sportelloRiferimento;
private String riferimento;
private String note;
private String accettazioneConsensoC1;
private String accettazioneConsensoC3;
}
I have to make a JSON request to map this object, I have made this but it is never seen as IntestatarioPrivacySospensiva object.
[
{
//this are intestatarioInput variable
"abi":"abi",
"cf":"cf",
"ndg":"ndg"
},
{//This are datiprivacy variable
"tipoConsenso":"tipoConsenso",
"consenso":"consenso"
},
{
"sportelloRiferimento":"sportelloRif",
"riferimento":"riferimento",
"note":"note",
"accettazioneConsensoC1":"true",
"accettazioneConsensoC3":"false"
}
]
My service have in the request ArrayList x; how i have to map it in json?
I'm using Postman to send JSON.
I believe this should work:
[{
"sportelloRiferimento":"sportelloRif",
"riferimento":"riferimento",
"note":"note",
"accettazioneConsensoC1":"true",
"accettazioneConsensoC3":"false",
"intestatario" : {
"abi":"abi",
"cf":"cf",
"ndg":"ndg"
},
"datiPrivacy" : [ {
"tipoConsenso":"tipoConsenso",
"consenso":"consenso"
} ]
},
{
"sportelloRiferimento":"sportelloRif",
"riferimento":"riferimento",
"note":"note",
"accettazioneConsensoC1":"true",
"accettazioneConsensoC3":"false",
"intestatario" : {
"abi":"abi",
"cf":"cf",
"ndg":"ndg"
},
"datiPrivacy" : [ {
"tipoConsenso":"tipoConsenso",
"consenso":"consenso"
} ]
}]
You can use Jackson 2.x to get JSON strings from your Java objects. Checkout the below example:
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
I am using jackson to map json which I get from my post rest api to map to a java object.
the json is represent by
{
"baseName": "xyz",
"salary": [
{
"id": 1,
"info": {
"ename": "john",
"eid": 143
}
},
{
"id": 2,
"info": {
"ename": "bg",
"eid": 123
}
}
]
}
The java class are represent by
BaseInfo.java
class BaseInfo {
String baseName;
ArrayList<salary> salaries = new ArrayList<salary>();
}
Salary.java
class Salary {
int id;
EmplInfo emp;
}
EmplInfo.java
class EmplInfo{
String ename;
int eid;
}
But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc
You can use the JsonProperty annotation to rename properties
class BaseInfo {
String baseName;
#JsonProperty("salary")
ArrayList<salary> salaries = new ArrayList<salary>();
}
class Salary {
int id;
#JsonProperty("info")
EmplInfo emp;
}
Following are the solutions:
Either add JsonProperty annotations as specified by Michael or update json keys i.e 'salary' to 'salaries' and 'info' to 'emp'
Looking to parse some Json and parse out array of arrays. Unfortunately I cannot figure out how to handle nested arrays within the json.
json
{
"type": "MultiPolygon",
"coordinates": [
[
[
[
-71.25,
42.33
],
[
-71.25,
42.33
]
]
],
[
[
[
-71.23,
42.33
],
[
-71.23,
42.33
]
]
]
]
}
What I have implemented when I just an a single array.
public class JsonObjectBreakDown {
public String type;
public List<List<String[]>> coordinates = new ArrayList<>();
public void setCoordinates(List<List<String[]>> coordinates) {
this.coordinates = coordinates;
}
}
parsing call
JsonObjectBreakDown p = gson.fromJson(withDup, JsonObjectBreakDown.class);
You've got an array of arrays of arrays of arrays of Strings. You need
public List<List<List<String[]>>> coordinates = new ArrayList<>();
The following
public static void main(String args[]) {
Gson gson = new Gson();
String jsonstr ="{ \"type\": \"MultiPolygon\",\"coordinates\": [ [ [ [ -71.25, 42.33 ], [ -71.25, 42.33 ] ] ], [ [ [ -71.23, 42.33 ], [ -71.23, 42.33 ] ] ] ]}";
JsonObjectBreakDown obj = gson.fromJson(jsonstr, JsonObjectBreakDown.class);
System.out.println(Arrays.toString(obj.coordinates.get(0).get(0).get(0)));
}
public static class JsonObjectBreakDown {
public String type;
public List<List<List<String[]>>> coordinates = new ArrayList<>();
public void setCoordinates(List<List<List<String[]>>> coordinates) {
this.coordinates = coordinates;
}
}
prints
[-71.25, 42.33]