How JSONArray to String - json

Sorry my English is not good.
This Code.
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
JSONArray arrJSON = new JSONArray();
JSONObject aJSON = new JSONObject();
aJSON.put("1","1");
aJSON.put("2","2");
arrJSON.add(aJSON);
JSONObject sJSON = new JSONObject();
sJSON.put("A", arrJSON.toString());
return sJSON.toString();
this is sJSON output:
{"A":[{"1":"1","2":"2"}]}
JSONArray is not String
How do i get this?
{"A":"[{\"1\":\"1\",\"2\":\"2\"}]"}
Thx ^_^

Related

Iterate over Json response with Multiple JSONArray And JSONObject

{
"Response":"success",
"errorText":null,
"TotalBooks":null,
"privateBookStore":{
"privateBooks":[
{
"Shopid":76354,
"Shopname":"xyz",
"Term":null,
"“Strategy":[
{
"Name":"ABC",
"ID":9
}
],
"magaerTYpe":"Single",
"Freq":"”monthly”",
"StructureType":{
"Name":"ABC",
"ID":9
},
"Currency":[
"USD",
"EURO",
"RUPYEE"
]
}
]
}
}
I have tried with JsonObject and JsonArray but the format of response is containing multiple JsonArray and JsonObject Together
I tried using HashMap and List but its not working for me. Loop through multiple JsonObject I have gone though this too.
Kindly suggest the approach
What I have so far is -
inputstream in = new bufferedinputstream(urlconnection.getinputstream());
String result = ioutils.tostring(in utf-8 );
JSONObject outer = new JSONObject(result);
JSONObject inner = outer.getJSONObject("privateBookStore");
JSONArray arr = inner.getJSONArray("privateBooks");
also tried with this too but not giving me key:value pair structure
List<HashMap<String,String>> response = new ArrayList<>();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(json);
for(int i=0;i<jsonarray.length();i++) {
JSONObject jsonObject = jsonarray.getJSONObject(i);
Iterator<?> iterator = jsonObject.keys();
HashMap<String,String> map = new HashMap<>();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = jsonObject.get(key.toString());
map.put(key.toString(),value.toString());
}
response.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}

How to insert the json data Array into existing json field?

I have the following JSON:
{
"X":20,
"Y":null
}
Now, for the key Y, i need to insert below json array.
{
"A":null,
"B":1,
"C":5000,
"D":0.25
}
I tried this but doesn't work:
String response1 =
given()
.cookie(apiTestSessionID)
//.spec(requestSpecification)
.when()
//.get("/service/bill/Config")
.get("/service/bill/Config/0001")
.asString();
JsonPath jsonCstmrConfig = new JsonPath(response);
String response2 = given()
.cookie(apiTestSessionID)
.when()
.get("/service/commoncache/card")
.asString();
JsonPath jsonSoiRateCard = new JsonPath(response2);
Map<String,String> maps = jsonCstmrConfig.getMap("data");
maps.put("X","Value");
Is there any way to do it with provided rest assured json library.
Try below code, it uses Gson library
Gson gson = new Gson();
String response1 = given()
.cookie(apiTestSessionID)
.when()
.get("/service/bill/Config/0001")
.asString();
//Converting response string to JsonObject
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
String response2 = given()
.cookie(apiTestSessionID)
.when()
.get("/service/commoncache/card")
.asString();
//Converting response string to JsonElement
JsonElement element = gson.fromJson (response2, JsonElement.class);
//Adding json data array to existing jsonObject
jsonObj.add("Y", element);

how do convert json string to a string

I have the json string from MySQL database:
{"teams":[{"sport":"NFL"},{"sport":"NBA"},{"sport":"NCAA Football"},{"sport":"NCAA Men Basketball"}],"success":1}
And I need to convert this string to the following format:
final String sports[] = {"NFL", "NBA", "NCAA Football", "NCAA Men Basketball"};
Any ideas how to do this?
import org.json.*;
String jsonString = yourJsonStringFromDatabase;
JSONObject obj = new JSONObject(jsonString);
JSONArray team = obj.getJSONArray("teams");
String[] sports = new String[team.length());
for (int i = 0; i < team.length(); i++)
{
sports[i] = arr.getJSONObject(i).getString("sport");
}

Using Gson and JsonObject to format and parse data

I am using JsonObject and Gson to format the data i need to send in the form of String and then retrieve and parse it somewhere else.
This is my simple code which is not working:
public static void main(String[] args)
{
Gson g = new Gson();
Gson listG = new Gson();
ArrayList<String> l= new ArrayList<String>();
l.add("abcd");
l.add("efgh");
l.add("ijkl");
String list = listG.toJson(l);
JsonObject jObject = new JsonObject();
jObject.addProperty("command" , 1);
jObject.addProperty("message" , "this is a test message");
jObject.addProperty("list" , list);
String toSend = g.toJson(jObject);
System.out.println(toSend);
Gson rec = new Gson();
JsonObject newObj = rec.fromJson(toSend, JsonObject.class);
System.out.println(newObj); // getting nothing in newObj
}
What am i doing wrong here?
You should use:
JsonObject newObj = new JsonParser().parse(toSend).getAsJsonObject();
Lots of calls in there, but the gist is to use the JsonParser class.

how to convert a JSON code to map

use the org.json.jar
I know convert a JSON code to JSONObject
JSONObject fieldsJson = new JSONObject("{\"a\":\"b\"}");
String value= fieldsJson.getString("a");
But how to convert a JSON code to map
String str = "{\"age\":\"23\",\"name\":\"ganlu\"}";
JSONObject jobj = JSONObject.fromObject(str);
Map<String,String> tmpMap = (Map) JSONObject.toBean(jobj,Map.class);
Set<String> keys = tmpMap.keySet();
for(String key : keys){
System.out.println(key+":"+tmpMap.get(key));
}
May this will help you.