How to get each value from JSON string - java

I have this JSON String and I need to get each docmanId and each dz so,I could loop through them and work with them.
I have tried using gson library to do that,but I dont seem to figure it out.
JSON Array :
[{"docmanId":1,"dz":"CR"},
{"docmanId":1,"dz":"EU"},
{"docmanId":1,"dz":"JD"},
{"docmanId":1,"dz":"LT"},
{"docmanId":10,"dz":"CR"},
{"docmanId":10,"dz":"EU"},
{"docmanId":10,"dz":"LT"},
{"docmanId":100,"dz":"CR"},
{"docmanId":100,"dz":"EU"},
{"docmanId":100,"dz":"JD"},
{"docmanId":100,"dz":"LT"},
{"docmanId":1000,"dz":"CR"},
{"docmanId":1000,"dz":"EU"},
{"docmanId":1000,"dz":"JD"},
{"docmanId":1000,"dz":"LT"},
{"docmanId":10000,"dz":"ES"},
{"docmanId":10000,"dz":"EU"},
{"docmanId":10000,"dz":"JD"},
{"docmanId":100000,"dz":"CR"},
{"docmanId":100000,"dz":"EU"},
{"docmanId":100000,"dz":"JD"},
{"docmanId":100000,"dz":"LT"},
{"docmanId":100001,"dz":"CR"},
{"docmanId":100001,"dz":"EU"},
{"docmanId":100001,"dz":"LT"},
{"docmanId":100002,"dz":"CR"},
{"docmanId":100002,"dz":"EU"},
{"docmanId":100002,"dz":"JD"},
{"docmanId":100003,"dz":"CR"},
{"docmanId":100003,"dz":"EU"},
{"docmanId":100003,"dz":"JD"},
{"docmanId":100003,"dz":"LT"},
{"docmanId":100004,"dz":"CR"},
{"docmanId":100004,"dz":"EU"},
{"docmanId":100004,"dz":"JD"},
{"docmanId":100005,"dz":"CR"},
{"docmanId":100005,"dz":"EU"},
{"docmanId":100005,"dz":"JD"},
{"docmanId":100005,"dz":"LT"},
{"docmanId":100006,"dz":"CR"},
{"docmanId":100006,"dz":"EU"},
{"docmanId":100006,"dz":"JD"},
{"docmanId":100006,"dz":"LT"},
{"docmanId":100007,"dz":"CR"},
{"docmanId":100007,"dz":"EU"},
{"docmanId":100007,"dz":"JD"}]

With org.json ,
JSONArray jSONArray = new JSONArray("your input array");
int length = jSONArray.length();
for (int i = 0; i < length; i++) {
JSONObject jSONObject= jSONArray.getJSONObject(i);
System.out.println(jSONObject.get("docmanId"));
System.out.println(jSONObject.get("dz"));
}

with jackson
String json = "[{\"docmanId\":1,\"dz\":\"CR\"},\n" +
"{\"docmanId\":1,\"dz\":\"EU\"},\n" +
"{\"docmanId\":1,\"dz\":\"JD\"},\n" +
"{\"docmanId\":1,\"dz\":\"LT\"},\n" +
"{\"docmanId\":10,\"dz\":\"CR\"},\n" +
"{\"docmanId\":10,\"dz\":\"EU\"},\n" +
"{\"docmanId\":10,\"dz\":\"LT\"},\n" +
"{\"docmanId\":100,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100,\"dz\":\"LT\"},\n" +
"{\"docmanId\":1000,\"dz\":\"CR\"},\n" +
"{\"docmanId\":1000,\"dz\":\"EU\"},\n" +
"{\"docmanId\":1000,\"dz\":\"JD\"},\n" +
"{\"docmanId\":1000,\"dz\":\"LT\"},\n" +
"{\"docmanId\":10000,\"dz\":\"ES\"},\n" +
"{\"docmanId\":10000,\"dz\":\"EU\"},\n" +
"{\"docmanId\":10000,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100000,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100000,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100000,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100000,\"dz\":\"LT\"},\n" +
"{\"docmanId\":100001,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100001,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100001,\"dz\":\"LT\"},\n" +
"{\"docmanId\":100002,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100002,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100002,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100003,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100003,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100003,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100003,\"dz\":\"LT\"},\n" +
"{\"docmanId\":100004,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100004,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100004,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100005,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100005,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100005,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100005,\"dz\":\"LT\"},\n" +
"{\"docmanId\":100006,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100006,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100006,\"dz\":\"JD\"},\n" +
"{\"docmanId\":100006,\"dz\":\"LT\"},\n" +
"{\"docmanId\":100007,\"dz\":\"CR\"},\n" +
"{\"docmanId\":100007,\"dz\":\"EU\"},\n" +
"{\"docmanId\":100007,\"dz\":\"JD\"}]";
ObjectMapper objectMapper = new ObjectMapper();
DocmanList docmanList = objectMapper.readValue(json, DocmanList.class);
//logic below
}
public class Docman {
private long docmanId;
private String dz;
public long getDocmanId() {
return docmanId;
}
public void setDocmanId(long docmanId) {
this.docmanId = docmanId;
}
public String getDz() {
return dz;
}
public void setDz(String dz) {
this.dz = dz;
}
}
public class DocmanList extends ArrayList<Docman> {
}

you can do it by generating a class convert it in java object of list.
first generate a class
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Example implements Serializable
{
#SerializedName("docmanId")
#Expose
private long docmanId;
#SerializedName("dz")
#Expose
private String dz;
private final static long serialVersionUID = 3195470113916852896L;
/**
* No args constructor for use in serialization
*
*/
public Example() {
}
/**
*
* #param docmanId
* #param dz
*/
public Example(long docmanId, String dz) {
super();
this.docmanId = docmanId;
this.dz = dz;
}
public long getDocmanId() {
return docmanId;
}
public void setDocmanId(long docmanId) {
this.docmanId = docmanId;
}
public Example withDocmanId(long docmanId) {
this.docmanId = docmanId;
return this;
}
public String getDz() {
return dz;
}
public void setDz(String dz) {
this.dz = dz;
}
public Example withDz(String dz) {
this.dz = dz;
return this;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("docmanId", docmanId).append("dz", dz).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(docmanId).append(dz).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(docmanId, rhs.docmanId).append(dz, rhs.dz).isEquals();
}
}
Now Tell it to parse a List (of Welcome) instead. Since List is generic you will typically use a **TypeReference**
List<Welcome> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Welcome>>(){});
use http://www.jsonschema2pojo.org/ to convert your json to java class.

You could parse it using JsonPath :
static String json = "...";
public static void main(String[] args) {
String pageName = JsonPath.read(json, "$.pageInfo.pageName");
System.out.println(pageName);
Integer posts = JsonPath.read(json, "$.posts.length()");
for(int i=0; i < posts; i++) {
String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id");
System.out.println(post_id);
}
}

Related

can't get the mockito to mock a public method of a public class

I am trying to mock the getMeasureAggregator() of ResultSetRow object - I don't seem to succeed. I am very new in writing mockito unit test.
I want the BuilSQL.formatMeasuer() goes to case 2: so what I have decided to do was mocking row.getMeasureAggregator.
Here is my BuildSQL class:
public class SQLBuilder {
public static String buildSQL(JsonObject requestData, JsonObject queryInfo) throws AcquisitionException {
JsonArray jArray = queryInfo.get("columns").getAsJsonArray();
Set<String> columns = new HashSet<>(jArray.size());
for (int i = 0; i < jArray.size(); i++) {
columns.add(jArray.get(i).getAsString());
}
List<ResultSetRow> selectedRows = new ArrayList<>();
List<ResultSetRow> retrievedRows = null;
retrievedRows = MetaDataProvider.executeMetadataRequest(queryInfo, requestData); // this method returns a collection of RetrievedResultSetRow
for (ResultSetRow retrievedRow: retrievedRows) {
if (//some condition evaluates to true) {
selectedRows.add(retrievedRow);
}
}
String sql = "";
String select = "SELECT ";
for (int i = 0; i < selectedRows.size(); i++) {
ResultSetRow row = selectedRows.get(i);
select += formatMeasure(row.getMeatureName(), row.getMeasureAggregator());
}
select = select.substring(0, select.length() - 1);
return sql;
}
private static String formatMeasure(String measureName, int measureAggregator) {
switch(measureAggregator) {
case 1:
return "sum(\"" + measureName + "\")" + " AS \"" + measureName + "\",";
case 2:
return "COUNT(\"" + measureName + "\")" + " AS \"" + measureName + "\",";
return measureName;
}
}
here is my ResultSetRow class:
public class ResultSetRow {
private final int iRow;
private final int measureAggregator;
public ResultSetRow(JsonObject dimensionMetadata) {
this.iRow = dimensionMetadata.get("ROW").getAsInt();
this.measureAggregator = dimensionMetadata.get("MEASURE_AGGR").getAsInt();
}
public int getMeasureAggregator() {
return measureAggregator;
}
}
here is how I am mocking
#RunWith(PowerMockRunner.class)
#PrepareForTest({ HanaClientRequestUtils.class, RetrievedResultSetRow.class })
public class HanaSQLBuilderTest {
private ResultSetRow resultSetRow;
private requestData;
private queryInfo
#Test
public void formatMeatureExecuteCase2() throws Exception{
resultSetRow = Mockito.mock(ResultSetRow.class);
PowerMockito.when(resultSetRow.getMeasureAggregator()).thenReturn(2);
String querySQL = HanaSQLBuilder.buildSQL(requestData, queryInfo);
System.out.println(querySQL);
}
}
}
I am not sure why row.getMeasureAggregator() does not return 2?
Additionally to my comments above (I am coding by hand, forgive me some mistakes).
You can try with adding a retrievedRows as a parameter in Your buildSQL method:
public static String buildSQL(
JsonObject requestData,
JsonObject queryInfo,
List<ResultSetRow> retrievedRows) throws AcquisitionException {
// ... rest of Your code adopted to new parameter
}
And then provide Your retrievedRows filled with mocks
#Test
public void formatMeatureExecuteCase2() throws Exception{
resultSetRow = Mockito.mock(ResultSetRow.class);
PowerMockito.when(resultSetRow.getMeasureAggregator()).thenReturn(2);
List<ResultSetRow> retrievedRowsMock = new ArrayList<>(1);
retrievedRowsMock.add(resultSetRow);
String querySQL = HanaSQLBuilder.buildSQL(requestData, queryInfo, retrievedRowsMock);
System.out.println(querySQL);
}
}
I hope it will guide You to solution.

Parsing from Json to Java Objects using GSON

I have JSON something lie that:
String json = "{'zadanie' : { "+
"'lista' : {" +
"'img': 'something.jpg'," +
"'opis': 'Prawdziwy minionek'," +
"'cena': 117.00," +
"'ilosc': 12," +
"'baza': ['truskawka - wanilia', 'sernik - pomarańcza', 'jagoda - wanilia', 'żurawina - wanilia', 'czekolada - wanilia', 'czekolada - banan', 'czekolada - cappuccino', 'tiramisu']," +
"'czas': '2 dni'"+
"}"+
"',lista2' : {" +
"'img': 'something2.jpg'," +
"'opis': 'Prawdziwy minionek'," +
"'cena': 117.00," +
"'ilosc': 12," +
"'baza': ['truskawka - wanilia', 'sernik - pomarańcza', 'jagoda - wanilia', 'żurawina - wanilia', 'czekolada - wanilia', 'czekolada - banan', 'czekolada - cappuccino', 'tiramisu']," +
"'czas': '2 dni'"+
"}"+
"]}}";
And I would like to parse it to object in Java. I have classes:
class Lista2{
private List<Lista> lista2;
public List<Lista> getLista2() {
return lista2;
}
public void setLista2(List<Lista> lista2) {
this.lista2 = lista2;
}
#Override
public String toString() {
return "GroupList{" + "lista2=" + lista2 + '}';
}}
//=================================================
class Lista {
private Data lista;
public Data getLista() {
return lista;
}
public void setLista(Data lista) {
this.lista = lista;
}
#Override
public String toString() {
return "Lista{" + "lista=" + lista + '}';
}}
//=================================================
class Data {
private String img;
private String opis;
private Double cena;
private Integer ilosc;
private List<String> baza;
private String czas;
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
public Double getCena() {
return cena;
}
public void setCena(Double cena) {
this.cena = cena;
}
public Integer getIlosc() {
return ilosc;
}
public void setIlosc(Integer ilosc) {
this.ilosc = ilosc;
}
public List<String> getBaza() {
return baza;
}
public void setBaza(List<String> baza) {
this.baza = baza;
}
public String getCzas() {
return czas;
}
public void setCzas(String czas) {
this.czas = czas;
}
#Override
public String toString() {
return "Data{" + "img=" + img + ", opis=" + opis + ", cena=" + cena + ", ilosc=" + ilosc + ", baza=" + baza + ", czas=" + czas + '}';
} }
Something is wrong, because I have error: "StandardWrapperValve[Glowna]: Servlet.service() for servlet Glowna threw exception
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 360
at com.google.gson.Gson.fromJson(Gson.java:809)"
For GSON parse:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
Lista2 userinfo1 = gson.fromJson(reader, Lista2.class);

Handling a .data file with uneven whitespaces delimited and populate to an bean object using java program

How to handle file data as shown below, which is delimited by uneven whitespaces, where if tokenizer is used based on space, it'll give tokens which cannot be assigned to java bean fields directly.
Below is the content Data of cheapdata4.data:
(TX 260816.<
0954F2003EGGPLEIBLNX37PU ZC550 Z <CA C A L L8 STAF P18 UL15 KIDL
0001F0148BIKFEDDSGWI2797 ZA319 Z <CATGWI2 C M V104 GMH4 GMH UL60 EDDS
4893F1416EGPGEGHFGJOID ZSR20 Z <AAEGPGD C A LT TLA DCS L612 N859 Q41
7945F1400EGSHEGCCLOG63JF ZD328 Z <(A C A R L OTBE Y70 EGCC
7946F1647EGSHEGGWAZE01F ZE50P Z <(A C A R LT MAM1 LAPR ABBO BKY2
7947F1701EGSHEGCCLOG63JF ZD328 Z <(A C A R L / MAM0 OTBE POL ROSU
4368F1657ESSBEGGWBLJ59BF ZC56X Z <RAUBLJ5 A LT UN86 UP7 UP25 EGGW
4369F1728ESSBEGCCETI226L MLJ45 012<RAUETI2 A L UL97 Y70 EGCC
4370F0551LHBPEGGWWZZ196 ZA321 Z <RAUWZZ1 A MT UL60 UY6 UM20 EGGW
7950END 260816.<
package com.msa.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.msa.bean.CheapData;
public class FinalParser {
public static void main(String[] args) {
BufferedReader reader;
try {
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(
new FileReader(
"C:\\Users\\Desktop\\assignment\\cheapdata4.data"));
System.out.println("Reading file...");
String line = reader.readLine();
line = line.replaceAll("\\s{2,}", " ");
String[] toks = line.replace(" ", ",").trim().split(",");
line = line.replaceAll("\\s{2,}", " ");
String[] headerTokens = line.split(" +");
String fileStartDate = headerTokens[1].substring(0, 6);
List<String> cheapDataContent = new ArrayList<>();
String[] lineTokens = { "" };
CheapData cheapFileDets = null;
List<CheapData> cheapDataList = new ArrayList<>();
while (line != null) {
line = reader.readLine();
line = line.replaceAll("\\s{2,4}", " ");
// line = line.replaceAll("\\s{2}", " NA ");
// line = line.replaceAll(" ",", ");
// line = line.replaceAll("\\,{2}", "");
lineTokens = line.split(" +");
int len = lineTokens.length;
// String fileEndDate ="";
if (len == 2) {
String fileEndDate = lineTokens[1].substring(0, 6);
if (fileStartDate.equals(fileEndDate)) {
break;
} else {
System.out.println("Date mismatch...");
}
}
if (len >= 6) {
cheapFileDets = new CheapData();
String lineNum = lineTokens[0].substring(0, 4);
cheapFileDets.setLineNum(lineNum);
String cheapReference = lineTokens[0].substring(4);
cheapFileDets.setCheapReference(cheapReference);
cheapFileDets.setDate(fileStartDate);
cheapFileDets.setAircraftCode(lineTokens[1]);
cheapFileDets.setIdentifierCode(lineTokens[2]);
cheapFileDets.setLicenseCode(lineTokens[3]);
if (lineTokens[4].equals("C"))
cheapFileDets.setCodeOne(lineTokens[4]);
else
cheapFileDets.setCodeOne(null);
if (lineTokens[5].equals("A"))
cheapFileDets.setCodeTwo(lineTokens[5]);
else
cheapFileDets.setCodeTwo(null);
if (lineTokens[6].equals("R"))
cheapFileDets.setCodeThree(lineTokens[6]);
else
cheapFileDets.setCodeThree(null);
} else {
if (len == 7)
cheapFileDets.setIdCode(lineTokens[7]);
else
cheapFileDets.setIdCode(null);
}
List<String> miscList = new ArrayList<>();
for (int i = 7; i < len - 1; i++) {
miscList.add(lineTokens[i]);
}
StringBuilder miscAll = new StringBuilder("");
for (String miscs : miscList) {
miscAll.append(miscs + " ");
}
cheapFileDets.setMiscAll(miscAll.toString());
cheapDataList.add(cheapFileDets);
}
System.out.println("File content" + sb.toString());
System.out.println("file date is: " + fileStartDate);
System.out.println("*************");
/*
* for (String strToks : lineTokens) { System.out.println(strToks);
* }
*/
// System.out.println(cheapDataList);
Iterator<CheapData> itrCheapData = cheapDataList.listIterator();
while (itrCheapData.hasNext()) {
System.out.println(itrCheapData.next());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
package com.msa.bean;
public class CheapData {
private String lineNum;
private String date;
private String cheapReference;
private String aircraftCode;
private String identifierCode;
private String licenseCode;
private String codeOne;
private String codeTwo;
private String codeThree;
private String idCode;
private String miscAll;
public String getLineNum() {
return lineNum;
}
public void setLineNum(String lineNum) {
this.lineNum = lineNum;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCheapReference() {
return cheapReference;
}
public void setCheapReference(String cheapReference) {
this.cheapReference = cheapReference;
}
public String getAircraftCode() {
return aircraftCode;
}
public void setAircraftCode(String aircraftCode) {
this.aircraftCode = aircraftCode;
}
public String getIdentifierCode() {
return identifierCode;
}
public void setIdentifierCode(String identifierCode) {
this.identifierCode = identifierCode;
}
public String getLicenseCode() {
return licenseCode;
}
public void setLicenseCode(String licenseCode) {
this.licenseCode = licenseCode;
}
public String getCodeOne() {
return codeOne;
}
public void setCodeOne(String lineTokens) {
this.codeOne = lineTokens;
}
public String getCodeTwo() {
return codeTwo;
}
public void setCodeTwo(String lineTokens) {
this.codeTwo = lineTokens;
}
public String getCodeThree() {
return codeThree;
}
public void setCodeThree(String codeThree) {
this.codeThree = codeThree;
}
public String getIdCode() {
return idCode;
}
public void setIdCode(String idCode) {
this.idCode = idCode;
}
public String getMiscAll() {
return miscAll;
}
public void setMiscAll(String miscAll) {
this.miscAll = miscAll;
}
public CheapData(String lineNum, String date, String cheapReference,
String aircraftCode, String identifierCode, String licenseCode,
String codeOne, String codeTwo, String codeThree, String idCode,
String miscAll) {
super();
this.lineNum = lineNum;
this.date = date;
this.cheapReference = cheapReference;
this.aircraftCode = aircraftCode;
this.identifierCode = identifierCode;
this.licenseCode = licenseCode;
this.codeOne = codeOne;
this.codeTwo = codeTwo;
this.codeThree = codeThree;
this.idCode = idCode;
this.miscAll = miscAll;
}
#Override
public String toString() {
return "CheapData [lineNum=" + lineNum + ", date=" + date
+ ", cheapReference=" + cheapReference + ", aircraftCode="
+ aircraftCode + ", identifierCode=" + identifierCode
+ ", licenseCode=" + licenseCode + ", codeOne=" + codeOne
+ ", codeTwo=" + codeTwo + ", codeThree=" + codeThree
+ ", idCode=" + idCode + ", miscAll=" + miscAll + "]";
}
public CheapData() {
super();
}
}
Please can anyone help me out in this regard. I want to parse above file and populate each columns from that to an object using setters in java.
Please do suggest me how to achieve this and kindly let me know if my query not clear.

JSON formatting for a Java Server

I am trying to read JSON string using gson into a Java program. In the sample code below - the Java program has 3 object classes. The data in the json string will have a variable number of object instances of each class. I have tried to create a sample JSON - to parse .. but had problems parsing the various objects.
Is this the right way to consume a json string or can it be done in a different way.. How would you parse a json with variable objects of different classes. Thanks,
package newpackage;
import java.util.ArrayList;
import com.google.gson.Gson;
public class jsonsample {
public static void main(String[] args) {
String jsonstring = "{'TableA':[{'field_A1':'A_11'},{'field_A1':'A_12'}]}"
+ ",{'TableB':[{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def','ghi']},"
+ "{'field_B1':'B_21','field_B2':'B_Field22','field_B3':['mno','pqr','xyz']}]"
+ ",{'TableC':[{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
+ "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'},{'field_C1':'C_31','field_C2':'C_32','field_C3':'C_33'}]}";
jsonstring = jsonstring.replace('\'', '"');
}
public class TableA {
String field_A1;
public TableA(String a){
this.field_A1 = a;
}
#Override
public String toString() {
return ("Table A" + " " + this.field_A1);
}
}
public class TableB {
String field_B1;
String field_B2;
ArrayList<String> field_B3 = new ArrayList<String>();
public TableB(String a, String b, ArrayList<String> c){
this.field_B1 = a;
this.field_B2 = b;
this.field_B3 = c;
}
#Override
public String toString() {
return ("Table B" + " " + this.field_B1+ " " + this.field_B2);
}
}
public class TableC {
String field_C1;
String field_C2;
String field_C3;
public TableC(String a, String b, String c){
this.field_C1 = a;
this.field_C2 = b;
this.field_C3 = c;
}
#Override
public String toString() {
return ("Table C" + " " + this.field_C1 + " " + this.field_C2 + " " + this.field_C3);
}
}
}
First of all you have to decide what is your base json structure ? Max identifiers, max values, max objects,max arrays...
Create your full json structure with texteditor or http://www.jsoneditoronline.org/ or http://jsonlint.com/ etc.
Let's think this is my full json structure:
{
"array": [
1,
2,
3
],
"boolean": true,
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
Create your Java Classes as like as your json identifiers. You can use http://json2csharp.com/ convert to Java.
And these are my Java Classes:
public class Object
{
public string a { get; set; }
public string c { get; set; }
public string e { get; set; }
}
public class RootObject
{
public ArrayList<int> array { get; set; }
public Boolean boolean { get; set; }
public Object #null { get; set; }
public int number { get; set; }
public Object #object { get; set; }
public string #string { get; set; }
}
Create your DAO for convert these to structure to them.
For Java;
String data = "jsonString";
RootObject root = new GsonBuilder().create().fromJson(data, RootObject.class);
For Json;
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
String json = gson.toJson(obj);
Your JSON-string seems incorrect to me. Let me propose the following:
public static void main(String args[]) {
String jsonstring = "["
+ "{'TableA':[{'field_A1':'A_11'},{'field_A1':'A_12'}]}"
+ ",{'TableB':[{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def','ghi']},"
+ "{'field_B1':'B_21','field_B2':'B_Field22','field_B3':['mno','pqr','xyz']}]}"
+ ",{'TableC':[{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
+ "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'},{'field_C1':'C_31','field_C2':'C_32','field_C3':'C_33'}]}"
+ "]";
jsonstring = jsonstring.replace('\'', '"');
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonstring).getAsJsonArray();
for (JsonElement jsonElement : array) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
Map.Entry<String,JsonElement> table = jsonObject.entrySet().iterator().next();
String tableName = table.getKey();
JsonElement rows = table.getValue();
try {
Class<?> rowClass = Class.forName("[Lnewpackage." + tableName + ";"); // explanation see below this code snippet
// rowClass is an array class!
Object[] parsedRows = gson.fromJson(rows, rowClass);
// do something with parsedRows
for (Object x : parsedRows) {
System.out.println(x);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Assuming a "table definition" consists of a property named as the class ob the objects in the table, with the objects as array value of that property.
Explanation of Class.forName("[Lnewpackage." + tableName + ";")
This retrieves the Class instance for the array type of a class located in the package newpackage, e.g. newpackage.TableA[] (note the []). Class.forName("A") returns the instance representing the class A. Class.forName("[LA;") returns the instance representing the "class" of an array of As. Using it as a parameter for fromJson(...) it results in the parsing of a JSON array of A-objects.
This is the code - that works based on #hurricane suggestion.
package newpackage;
import java.util.List;
import com.google.gson.*;
public class jsonsample {
public static void main(String[] args) throws ClassNotFoundException {
String jsonstring = "{'TableA':["
+ "{'field_A1':'A_11'},"
+ "{'field_A1':'A_12'}"
+ "],"
+ "'TableB':["
+ "{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def']},"
+ "{'field_B1':'B_21','field_B2':'B_22','field_B3':['mno','xyz']}"
+ "],"
+ "'TableC':["
+ "{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
+ "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'}"
+ "]}";
jsonstring = jsonstring.replace('\'', '"');
RootObject root = new GsonBuilder().create().fromJson(jsonstring, RootObject.class);
for (int i=0; i < root.TableA.size(); i++){
System.out.println(root.TableA.get(i));
}
for (int i=0; i < root.TableB.size(); i++){
System.out.println(root.TableB.get(i));
}
for (int i=0; i < root.TableC.size(); i++){
System.out.println(root.TableC.get(i));
}
}
public class TableA
{
public String field_A1;
#Override
public String toString() {
return ("Table A" + " " + this.field_A1);
}
}
public class TableB{
public String field_B1;
public String field_B2;
public List<String> field_B3;
#Override
public String toString() {
return ("Table B" + " " + this.field_B1 + " " + this.field_B2 + " " + this.field_B3);
}
}
public class TableC{
public String field_C1;
public String field_C2;
public String field_C3;
#Override
public String toString() {
return ("Table C" + " " + this.field_C1 + " " + this.field_C2 + " " + this.field_C3);
}
}
public class RootObject{
public List<TableA> TableA;
public List<TableB> TableB;
public List<TableC> TableC;
}
}
The output for the above is:
Table A A_11
Table A A_12
Table B B_11 B_12 [abc, def]
Table B B_21 B_22 [mno, xyz]
Table C C_11 C_12 C_13
Table C C_21 C_22 C_23

generating a number between a range using json

How can we generate a number between a range using Json.
Like we have to generate a number between 0 to 50, how can we perform this in Java using a Json.
This is my Json Data
{
"rand": {
"type': "number",
"minimum": 0,
"exclusiveMinimum": false,
"maximum": 50,
"exclusiveMaximum": true
}
}
This is what I have tried in Java
public class JavaApplication1 {
public static void main(String[] args) {
try {
for (int i=0;i<5;i++)
{
FileInputStream fileInputStream = new FileInputStream("C://users/user/Desktop/V.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("POI Worksheet");
HSSFRow row1 = worksheet.getRow(0);
String e1Val = cellE1.getStringCellValue();
HSSFCell cellF1 = row1.getCell((short) 5);
System.out.println("E1: " + e1Val);
JSONObject obj = new JSONObject();
obj.put("value", e1Val);
System.out.print(obj + "\n");
Map<String,Object> c_data = mapper.readValue(e1Val, Map.class);
System.out.println(a);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
Json Data is stored in excel sheet, from there I am reading it in Java program
Get a Json-reader like GSON.
Read in the JSON to an equivalent Object like
public class rand{
private String type;
private int minimum;
private boolean exclusiveMinimum;
private int maximum;
private boolean exclusiveMaximum;
//this standard-constructor is needed for the JsonReader
public rand(){
}
//Getter for all Values
}
and after reading in your JSON you can access your Data via your getter-methods
I think that Jackson may be of help here.
I suggest that you create a data model in Java that reflects the JSON. This can along the lines of:
// This is the root object. It contains the input data (RandomizerInput) and a
// generate-function that is used for generating new random ints.
public class RandomData {
private RandomizerInput input;
#JsonCreator
public RandomData(#JsonProperty("rand") final RandomizerInput input) {
this.input = input;
}
#JsonProperty("rand")
public RandomizerInput getInput() {
return input;
}
#JsonProperty("generated")
public int generateRandomNumber() {
int max = input.isExclusiveMaximum()
? input.getMaximum() - 1 : input.getMaximum();
int min = input.isExclusiveMinimum()
? input.getMinimum() + 1 : input.getMinimum();
return new Random().nextInt((max - min) + 1) + min;
}
}
// This is the input data (pretty much what is described in the question).
public class RandomizerInput {
private final boolean exclusiveMaximum;
private final boolean exclusiveMinimum;
private final int maximum;
private final int minimum;
private final String type;
#JsonCreator
public RandomizerInput(
#JsonProperty("type") final String type,
#JsonProperty("minimum") final int minimum,
#JsonProperty("exclusiveMinimum") final boolean exclusiveMinimum,
#JsonProperty("maximum") final int maximum,
#JsonProperty("exclusiveMaximum") final boolean exclusiveMaximum) {
this.type = type; // Not really used...
this.minimum = minimum;
this.exclusiveMinimum = exclusiveMinimum;
this.maximum = maximum;
this.exclusiveMaximum = exclusiveMaximum;
}
public int getMaximum() {
return maximum;
}
public int getMinimum() {
return minimum;
}
public String getType() {
return type;
}
public boolean isExclusiveMaximum() {
return exclusiveMaximum;
}
public boolean isExclusiveMinimum() {
return exclusiveMinimum;
}
}
To use these classes the ObjectMapper from Jackson can be used like this:
public static void main(String... args) throws IOException {
String json =
"{ " +
"\"rand\": { " +
"\"type\": \"number\", " +
"\"minimum\": 0, " +
"\"exclusiveMinimum\": false, " +
"\"maximum\": 50, " +
"\"exclusiveMaximum\": true " +
"} " +
"}";
// Create the mapper
ObjectMapper mapper = new ObjectMapper();
// Convert JSON to POJO
final RandomData randomData = mapper.readValue(json, RandomData.class);
// Either you can get the random this way...
final int random = randomData.generateRandomNumber();
// Or, you can serialize the whole thing as JSON....
String str = mapper.writeValueAsString(randomData);
// Output is:
// {"rand":{"type":"number","minimum":0,"exclusiveMinimum":false,"maximum":50,"exclusiveMaximum":true},"generated":21}
System.out.println(str);
}
The actual generation of a random number is based on this SO question.

Categories