I have to read a sample pom file and write all technology and version in to json file, Im able to get the output in this format:
["{ name:junit ,Version:4.12}","{ name:spring-batch-test ,Version:3.0}","{ name:spring-boot-starter }","{ name:slf4j-api }"]
However I want to get output in this format:
[{ "name":"junit" ,"Version":"4.12"},{" name":"spring-batch-test" ,"Version":"3.0"},{"name":"spring-boot-starter" }]
My code :
Map<String, String> dependencies = Maps.newHashMap();
dependencies = populateProjectDepedencies(dependencies, pomFile);
In populateProjectDependencies
for (Dependency dependency : dependencyList) {
String version = "0.0";
if (dependency.getVersion() != null &&
dependency.getVersion().startsWith("${"))
{
version = (String) properties.get(dependency.getVersion()
.substring(2, dependency.getVersion().length() - 1));
} else {
version = dependency.getVersion();
}
if (version != null) {
String a1[]=version.split("\\.");
int i=a1.length;
if(i>=2)
{
version=a1[0]+"."+a1[1];
}
dependencies.put("{name:"+dependency.getArtifactId(),",
Version:"+version+"}" );
JSONArray jsonArray = prepareJsonObject(dependencies);
genarateTechnologyRadarJson(jsonArray);
writer.write(jsonArray.toJSONString());
As I understand from your question, you are holding json as String array but you want to hold data as JSONObject array. So,
JSONArray ja = new JSONArray();
for (Dependency dependency : dependencyList) {
.....
JSONObject obj=new JSONObject();
obj.put("name",dependency.getArtifactId());
obj.put("Version",version);
ja.put(obj);
//remove dependencies.put,JSONArray. and genarateTechnologyRadarJson(jsonArray);
}
writer.write(ja.toString());
UPDATE
This should be your complete code
JSONArray jsonArray = new JSONArray();
for (Dependency dependency: dependencyList) {
String version = "0.0";
if (dependency.getVersion() != null &&
dependency.getVersion().startsWith("${")) {
version = (String) properties.get(dependency.getVersion()
.substring(2, dependency.getVersion().length() - 1));
} else {
version = dependency.getVersion();
}
if (version != null) {
String a1[] = version.split("\\.");
int i = a1.length;
if (i >= 2) {
version = a1[0] + "." + a1[1];
}
}
JSONObject obj=new JSONObject();
obj.put("name",dependency.getArtifactId());
obj.put("Version",version);
jsonArray.put(obj);
}
writer.write(jsonArray.toJSONString());
Because, you are adding the value as a String
"{ name:"+dependency.getArtifactId(),"
Even, I'm not sure why are you manually constructing the JSON instead just pass the Map object to JSONObject.
JSONObject obj=new JSONObject(yourmap);
Related
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);
JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air
Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.
try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");
Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.
I have a json file like below and want to parse the overlays like overlay1,overlay2,overlay3:
{
"overlays": {
"overlay1": {
"imagesFPS": 12,
"clickThrough": false,
"repeatCount": 0,
"sensitivity": 0.6,
},
"overlay2": {
"cgButtonPressedColor": "#ffaa56",
"relative": "screen",
"isOverlayRendered": true,
"cgBorderWidth": "0px",
},
"overlay3": {
"cgButtonPressedColor": "#007f00",
"text": "Goto Page3 on Touch 5 Release",
}
}
}
Currently I am doing this:
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
for (int i = 1; i <= 100; i++) {
JsonObject overlay = ovl.getAsJsonObject("overlay" + i);
if (overlay != null) {
osb.setOverlay(jsp.getOverlay(overlay));
}
}
How can I get the length of overlays (here: overlay1, overlay2, overlay3)? How do I query the length of 3 via the gson API?
And I want to know the overlay1,overlay2,overlay3 in a string or array so that I can iterate over them.
Note: Here I have to iterate 100 times or any times so that I can iterate if overlays increase later in json file. It iterates unnecessarily in looping.
How can I iterate only overlay1 or overlay2 or overlay3 and so without unnecessary iterating?
I mean I just want to get the overlay1, overlay2, overlay3 and so on in jsonobjects via Gson.
I have solved this using this code below.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
Map<String, Object> data = new Gson().fromJson(ovl, type);
Iterator<String> entries = data.keySet().iterator();
while (entries.hasNext())
{ JsonObject overlay = ovl.getAsJsonObject(entries.next().toString());
if (overlay != null)
{
osb.setOverlay(jsp.getOverlay(overlay));
}
}
Have you considered using an array instead of wrapped objects?
{
"overlays": [
{"overlay1": {
"imagesFPS": 12,
"clickThrough": false,
"repeatCount": 0,
"sensitivity": 0.6,
}},
{"overlay2": {
"cgButtonPressedColor": "#ffaa56",
"relative": "screen",
"isOverlayRendered": true,
"cgBorderWidth": "0px",
}},
{"overlay3": {
"cgButtonPressedColor": "#007f00",
"text": "Goto Page3 on Touch 5 Release",
}}
]
}
And using this code:
Gson gson = new Gson();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonArray ovl = job.getAsJsonArray("overlays");
if (ovl != null) {
osb.setOverlay(jsb.getOverlay(ovl.get(ovl.lenght() - 1)));
}
Or if you want to use wrapped json objects, you should create a list and insert elements like this:
Gson gson = new Gson();
List<JsonObject> overlays = new LinkedList<>();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
for (int i = 1; ; ++i) {
JsonObject overlay = ovl.getAsJsonObject("overlay" + i);
if (overlay == null) {
break;
} else {
overlays.put(overlay);
}
}
// Use "overlays" list
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);
}
I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling