I have a list and I want to convert it to json.
Here is my code
JqGridModel gridModel1 = new JqGridModel();
Date FromDate = new Date("1996-07-04");
Date ToDate = new Date("1996-07-05");
gridModel1.setOrderID(10248);
gridModel1.setFromDate(FromDate);
gridModel1.setToDate(ToDate);
gridModel1.setCustomerID("WILMK");
gridModel1.setShipName("Vins et alcools Chevalier");
JqGridModel gridModel2 = new JqGridModel();
Date FromDate2 = new Date("1996-07-04");
Date ToDate2 = new Date("1996-07-05");
gridModel2.setOrderID(10248);
gridModel2.setFromDate(FromDate2);
gridModel2.setToDate(ToDate2);
gridModel2.setCustomerID("WILMK");
gridModel2.setShipName("Vins et alcools Chevalier");
List jqGridModels = new ArrayList();
jqGridModels.add(gridModel1);
jqGridModels.add(gridModel2);
And I want to convert it to be in the following format:
{
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10252","FromDate":"1996-07-09","CustomerID":"SUPRD","ShipName":"Supr\u00eames d\u00e9lices","ToDate":"1996-08-01"}
]
}
Any help would be greatly appreciated.
Firstly: use generics
List jqGridModels = new ArrayList(); //bad
List<JqGridModel> jqGridModels = new ArrayList<>(); //good
Secondly: Can you use Gson?
List<JqGridModel> jqGridModels = new ArrayList<>();
Gson gson = new Gson();
JsonElement jsElem = gson.toJsonTree(jqGridModels, new TypeToken<List<JqGridModel>>() {}.getType());
if (! jsElem.isJsonArray()) {
//this is an error...
}
JsonArray jsonArray = jsElem.getAsJsonArray();
Haven't tested it yet but it should work, I'm doing this in my project and it's ok, if you have more troubles please tell me!
If you want to do it manually you can :
Create a method to generate the JSON from tour object :
class JqGridModel{
public JSONObject toJSON(){
JSONObject json = new JSONObject();
json.accumulate("OrderID", orderID);
// DO the same for all attributes
return json;
}
}
And then call this method looping on the list content :
JSONObject json = new JSONObject();
JSONArray arr = new JSONArray();
for(JqGridModel m: jqGridModels){
arr.put(m.toJSON());
}
json.accumulate("rows", arr);
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
StringBuffer result = new StringBuffer("{\n\t\"rows\":[\n");
try {
for(Object item : jqGridModels){
result = result.append("\t\t\t");
result = result.append(mapper.writeValueAsString(item));
result = result.append("\n");
}
if(jqGridModels.size() > 1){
result = result.append("\t]\n}");
System.out.print(result);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Related
I want list item should be with double quotes.
i tried like this :
List<String> langList = new ArrayList<>();
for (Language obj : language) {
langList.add(obj.getCode());
}
JSONObject where = new JSONObject();
try {
JSONObject languages = new JSONObject();
languages.put("$in", langList);
where.put("languages", languages);
} catch (JSONException e) {
e.printStackTrace();
}
result of langList is : "[en, ta, hi]"
and I added double quotes for items using langList.add("\"" + obj.getCode() + "\"");
now, It returns the result is : "[\"en\", \"ta\", \"hi\"]"
I don't want outside double quotes also.
am expecting result is : ["en", "ta", "hi"]
I have added an extra " to both sides before adding them to the list. PFB the code snippet.
String array[] = new String[] {"en","ta", "hi"};
List<String> langList = new ArrayList<>();
for (String item : array) {
langList.add("\""+item+"\"");
}
System.out.println("langList: "+ langList);
try {
JSONArray jsonObject = new JSONArray(langList.toString());
System.out.println("jsonObject: "+jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
I could see below logs in console.
langList: ["en", "ta", "hi"]
jsonObject: ["en","ta","hi"]
Hope this helps.
Note: Used org.json.JSONArray and org.json.JSONException classes in above code.
You can simply use:
langList.add('"' + obj.getCode() + '"');
try this
List<String> langList = new ArrayList<>();
for (Language obj : language) {
langList.add('"'+obj.getCode()+'"');
}
Add double quotes for items using this:
List<String> langList = new ArrayList<>();
for (Language obj : language) {
langList.add('"'+obj.getCode()+'"');
}
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.
My error :
JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray
My JSON:
{
"jsonData" : {
"11-13-2017" : {
"Clau" : {
"-KyokKjL9UQpsfKZYZqM" : [ {
"pret" : "80",
"produs" : "Shirt",
"produsId" : "-Kyok58s0dOAnVOnbJPk"
} ]
}
}
}
}
I looked over tutorials on StackOverFlow but absolutely no solution.
My code :
private void writeJSON(String metodaPlata) throws JSONException {
String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
int totalPrice = 0;
for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
{
int vPrice = Integer.parseInt(v.getPret());
totalPrice = totalPrice + vPrice;
}
String pretTotal = Integer.toString(totalPrice);
String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());
JSONObject jsonData;
JSONArray dateJSON;
JSONObject obj;
JSONArray arrayForList;
if (jsonDataFromShared.equals("")) {
jsonData = new JSONObject();
dateJSON = new JSONArray();
obj = new JSONObject();
arrayForList = new JSONArray();
JSONObject objListaSiModalitate = new JSONObject();
// arrayForList.put(stock_list.toString());
objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON.toString());
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
} else {
jsonData = new JSONObject(jsonDataFromShared);
dateJSON = jsonData.getJSONArray("jsonData");
obj = new JSONObject();
JSONObject objListaSiModalitate = new JSONObject();
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("produseSelectate", produseSelectate);
obj.put("sumaProduse", pretTotal);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON);
System.out.println("jsonData" + dateJSON);
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
}
}
Please help me I have no idea what to idea even if I look over tutorials.
I think your json parsing will be,
try {
JSONObject jsonObject = new JSONObject("jsonData");
JSONObject jsonObject1 = jsonObject.getJSONObject("11-13-2017");
JSONObject jsonObject2 = jsonObject1.getJSONObject("Clau");
JSONArray jsonArray = jsonObject2.getJSONArray("-KyokKjL9UQpsfKZYZqM");
JSONObject jsonObject3 = (JSONObject) jsonArray.getJSONObject(0);
String string = jsonObject3.getString("pret");
String string1 = jsonObject3.getString("produs");
String string2 = jsonObject3.getString("produsId");
} catch (JSONException e) {
e.printStackTrace();
}
Error causes from this line
jsonData.put("jsonData", dateJSON.toString());
Here dateJSON.toString() store the string value to jsonData variable. jsonData is JsonObject.
Then You try to retrieve JsonArray from string
jsonData = new JSONObject(jsonDataFromShared); //This line convert your string to jsonobject.
dateJSON = jsonData.getJSONArray("jsonData");
EDITED
If you want to retreive array from dateJson object
Replace this line
jsonData.put("jsonData", dateJSON.toString());
To
jsonData.put("jsonData", dateJSON);
I am using org.json library and am trying to create JSON Object stops in the simple form as below but I am always getting all timeEntries in the same JSONArray timeArray and the name is always changes in the stops as in the current output
Current output:
{"arrival_time":
{"mon-fri":[
["04:48","05:18","05:46","06:16"],
["04:52","05:22","05:50","06:20"],
["04:57","05:27","05:56","06:26"]
]
},
"stops_name":"third name"}
Code:
ArrayList<String> result = new ArrayList<String>();
JSONObject stops = new JSONObject();
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String name = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
stops.put("stops_name", name);
JSONArray timeArray = new JSONArray(timeEntries);
arrivalMoFr.put( timeArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
Simple how should the result like
{"arrival_time":
{"mon-fri":["04:48","05:18","05:46","06:16"]
}
"stops_name":"first name"},
{"arrival_time":
{"mon-fri":["04:52","05:22","05:50","06:20"]
}
"stops_name":"second name"},
{"arrival_time":
{"mon-fri":["04:57","05:27", "05:56","06:26"]
}
"stops_name":"third name"}
Keep in mind that you want an array as your root object. You'll have to create the other array and objects multiple times, so initializing them outside the for loop isn't useful.
ArrayList<String> result = new ArrayList<String>();
JSONArray stops = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String name = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
JSONObject stop = new JSONObject();
stop.put("stops_name", name);
JSONArray timeArray = new JSONArray(timeEntries);
//arrivalMoFr.put( timeArray);
JSONObject arrivals = new JSONObject();
arrivals.put("mon-fri", timeArray);
stop.put("arrival_time", arrivals);
stops.put(stop);
//System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm trying to parse Json string using java, I have stuck up with some scenario.
See below is my JSON String:
"NetworkSettings": {
"Ports": {
"8080/tcp": [ // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
}
I try to parse the above json string by using the following code:
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
if(ntw_Ports_obj.has("8080/tcp"))
{
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
if(ntwtcp_obj.has("HostIp"))
{
ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
System.out.println("Network HostIp = "+ntw_HostIp);
}
if(ntwtcp_obj.has("HostPort"))
{
ntw_HostPort=ntwtcp_obj.get("HostPort").toString();
System.out.println("Network HostPort = "+ntw_HostPort);
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
In my code I have used this code
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
to get the value of "8080/tcp"
How can I get the values of dynamically changing key like ("8125/udp","8134/udp", etc...)
Note: I'm using gson library for parsing
After modification
public static void main(String args[])
{
try
{
JsonParser parser = new JsonParser();
JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
System.out.println("obj = "+obj);
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
System.out.println(keyObjects instanceof Map); //**** here the statement prints false
if (keyObjects instanceof Map) // *** so controls doesn't enters into the if() condition block *** //
{
Map map = (Map) keyObjects;
System.out.println("Map = "+map);
keys.addAll(map.keySet());
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println("Array List = "+jArray);
}
}
}
catch(Exception e)
{
}
}
You can do something like that (not tested but should be ok) :
if (ntw_Ports_obj.isJsonArray()) {
Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();
while (it.hasNext()) {
JsonElement element = (JsonElement) it.next();
if(element.isJsonArray()){
JsonArray currentArray = element.getAsJsonArray();
// Do something with the new JsonArray...
}
}
}
So your problem is the key 8080/tcp is not fixed and it may change. when this situation you can try like this to get the value of the Dynamic key.
Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Edit:
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
Map map = (Map) keyObjects;
keys.addAll(map.keySet());
/**
* keys is a List it may contain more than 1 value, but for the given
* json it will contain only one value
**/
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Here, I have a String which has JSONObject inside it like this :
String a = "{"company_name":"ABC","company_address":"hgfh"}";
I added this JSONObject into String with this code :
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
a = company_one1.toString();
But now I've only the String and I need to add the JSONObject of this String a into an ArrayList and then convert that ArrayList into JSON which should look like :
{"id":"5","data":[{"company_name":"ABC","company_address":"hgfh","image":["cmFodWxtaXNocmE="]}]}
I have tried lots of things to change format like this, but I'm not getting exact format. Sometimes it adds backslashes \ itself into JSON beacuse we can't create a JSON which is already a JSON.
Please give me a proper solution for it.
Thanks in advance.
try this,
JSONArray imageArray = new JSONArray();
imageArray.put("cmFodWxtaXNocmE=");
//* you can add more to the image array by using the put method
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
//* add the image array
company_one1.put("image", imageArray);
//* create a JSONArray for company types,
JSONArray dataArray = new JSONArray();
dataArray.put(company_one1);
//* you can add more to the array here by using the put method
//* now put all in one main JSONObject
JSONObject mainObj = new JSONObect();
mainObj.put("id", "5");
mainObj.put("data", dataArray);
String finalJsonString = mainObj.toString();
I don't think you are handling with JSON in a right wary. Maybe you should do like this:
try {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("company_name", "company_name");
map1.put("company_address", "company_address");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("company_name", "company_name");
map2.put("company_address", "company_address");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("company_name", "company_name");
map3.put("company_address", "company_address");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map1);
list.add(map2);
list.add(map3);
JSONArray jsonArray = new JSONArray(list);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", "5");
jsonObject1.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Here is the link, if you wish to use GSON as library to serialize and de-serialize json data. Visit Tutorail Java Object to/from JSON and library Gson
Here is pseudo code.(so it could not be compiled maybe)
But Gson is pretty easy and useful.
class Company {
String name;
... // constructors, getter/setters...
}
class CompanyGroup {
int id;
List<Company> companies;
... // constructors, getter/setters...
}
String name = "ABC";
Company a = new Company(name);
int id = 5;
CompanyGroup g = new CompanyGroup(5);
g.companies.add(a);
String r = new Gson().toJson(g);
System.out.println(r);
// I/System.outīš {"companies":[{"name":"ABC"}],"id":5}