how to convert a JSON code to map - json

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.

Related

Deserializing Json String which is stored in a string variable

I am working in VS 2015 and c#.
I have a Json String which has a list of collections, each collection represents an object,
string wsjson =
"{
"customAttributes":
[{"description":"xxxxxxx","id":11,"value":"xxxxxxx"},{"description":"xxxxxxx","id":10,"value":"xxxxxxx"}],
"location":{"account":"xxxxxxx","cabinet":"xxxxxxx"},
"misc":{"approved":false,"archived":false,"deleted":false,"echo":true,"external":false,"favorite":false,"officialLocked":false,"signed":false},
"permissions":[{"xxxxxxx":true,"xxxxxxx":false,"edit":true,"noAccess":false,"share":true,"view":true}],
"standardAttributes":{"aclStatus":"xxxxxxx","created":"\/Date(xxxxxxx)\/","createdBy":"xxxxxxx","createdByGuid":"xxxxxxx","envId":"xxxxxxx","extension":"ndws","id":"xxxxxxx","modified":"\/Date(xxxxxxx)\/","modifiedBy":"xxxxxxx","modifiedByGuid":"xxxxxxx","name":"xxxxxxx","officialVer":1,"size":4,"syncMod":xxxxxxx,"url":"xxxxxxx","versions":1}}"
DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
I am getting an error. I tried to follow this (Deserializing Json String into multiple Object types) solution but I am getting error for this line as my jason data is in a string and no function to parse string.
var j = JArray.Parse(data);
Here is the visual image of the jason data.
Actual code block in my program is:
foreach (DataRow row in dataTable.Rows)
{
string wsjson = GetWorkspaceProfile(row[0].ToString());
DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
DataTable wsdataTable = wsdataSet.Tables["standardAttributes"];
foreach (DataRow wsrow in wsdataTable.Rows)
{
cmbWorkspaceByCabinet.Items.Add(new KeyValuePair<string, string>(row["envId"].ToString(), wsrow["name"].ToString()));
}
}
Where GetWorkspaceProfile is a string type return function which return me JSON data as string like the image above.
public string GetWorkspaceProfile(string WorkspaceId)
{
string responseStr = "";
string url = "v1/Workspace/" + WorkspaceId + "/info";
RestType type = RestType.GET;
Boolean useXml = false;
RestRequest rr = FormRequest(type, url, useXml);
IRestResponse response;
try
{
response = executeRequest(rr);
responseStr = response.Content;
}
catch (Exception ex)
{
return null;
}
return responseStr;
}
JArray.Parse will not work, because you don't have a json array, it is an object. Also not the all values of that object are collections, for example location is also object, not a collection. You have some options to parse it
Parse root object into Dictionary
JsonConvert.DeserializeObject<Dictionary<string, string>>(wsjson)
then parse every value of the dictionary to array if value is array and to dictionary if value is object.
Create a C# class according to your json data and parse string directly into instance of that class
JsonConvert.DeserializeObject<JsonModel>(wsjson);
where JsonModel is the class you need to create.
You can use JArray and JToken to get the values you want using json path.

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);

read data from a json formatted object

I have a .net application in which I am getting a response data in json format. I have used the below code to get the json response.
string details= new System.Net.WebClient().DownloadString(url);
var temp = JsonConvert.DeserializeObject(details.ToString());
I have got a json format object in temp and json format string in details
I am getting an output as below from temp
{"data":
[
{"category":"Community","name":"New Page","access_token":"accesstoken_data1","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"1234"},
{"category":"Community","name":"Page ABC","access_token":"accesstoken_data2","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"56789"}
]
,"paging":{"next":"https:\/\/graph.facebook.com\/1100234567\/accounts?access_token=pageAccesstoken&limit=5000&offset=5000&__after_id=77786543"}
}
I need to get the category,name,access_token as key and corresponding data as values in some dictionary.
How can I achieve it?
Hope this will do the required stuffs
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
This was taken from the following link
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
string json = #"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>
More examples: Serializing Collections with Json.NET

GWT HashMap to/from JSON

I might be getting a bit tired tonight but here it goes:
I'd like to have GWT HashMap to/from JSON. How would I achieve this?
In other words, I'd like to take an HashMap, take its JSON representation, store it somewhere and get it back to its native Java representation.
Here is my quick solution:
public static String toJson(Map<String, String> map) {
String json = "";
if (map != null && !map.isEmpty()) {
JSONObject jsonObj = new JSONObject();
for (Map.Entry<String, String> entry: map.entrySet()) {
jsonObj.put(entry.getKey(), new JSONString(entry.getValue()));
}
json = jsonObj.toString();
}
return json;
}
public static Map<String, String> toMap(String jsonStr) {
Map<String, String> map = new HashMap<String, String>();
JSONValue parsed = JSONParser.parseStrict(jsonStr);
JSONObject jsonObj = parsed.isObject();
if (jsonObj != null) {
for (String key : jsonObj.keySet()) {
map.put(key, jsonObj.get(key).isString().stringValue());
}
}
return map;
}
Not the most optimized, but should be easy to code: use JSONObject.
Iterate over your map's entries and put them in a JSONObject (converting each value to a JSONValue of the appropriate type), then call toString to get the JSON representation.
For parsing, get a JSONObject back using a JSONParser, then iterate over the keySet, geting the values and putting them in your map (after unwrapping the JSONValues)
But beware of the keys you use! You cannot use any kind of key as a property name in JS; and JSON processing in the browser always involve going through a JS object (or implementing the JSON parser yourself, which won't perform the same)

how to Convert string into Json using Newton Json library

sorry for the silly question, but i am stuck converting for example the following result from a method into Json
public string Test(string input) {
return "Name:" + input;
}
to look like this
{"Name":"Mike"}
Update:
Darin fixed first problem now i am using this way but it is not working
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using(JsonWriter jsonWriter = new JsonTextWriter(sw)) {
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WritePropertyName("Name");
jsonWriter.WriteValue("Mike");
}
I get
'{"Name":{"m_MaxCapacity":2147483647,"Capacity":16,"m_StringValue":"\\"Name\\": \\"Mike\\"","m_currentThread":0}}';
You could use the JavaScriptSerializer class:
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
Example usage:
string json = Test("Mike"); // json = {"Name":"Mike"}
UPDATE:
Didn't notice you wanted a solution using the Json.NET library. Here's one:
string json = JsonConvert.SerializeObject(new { Name = input });