Convert Json String to ArrayList - json

I have a json string and need to create an ArrayList where array values have to be inserted in the index position according with the ID value in the json string.
This is an example of the json String:
{"clients":{"1":"Client 1","2":"Client 2","3":"Client 3"}}
I use this code:
List<String> clientsArray = new ArrayList<String>();
String JsonR = '{"clients":{"1":"Client 1","2":"Client 2","3":"Client 3"}}';
JSONObject lJSONObject = new JSONObject(JsonR);
JSONArray lJSONArray = lJSONObject.getJSONArray("clients");
for (int i = 0; i < lJSONArray.length(); i++)
clientsArray.add(Integer.valueOf(lJSONArray.getJSONObject(i).getString("ID")), lJSONArray.getJSONObject(i).getString("Name"));
}
I get this error:
org.json.JSONException: Value {"1":"Client 1","2":"Client 2","3":"Client 3"} at clients of type org.json.JSONObject cannot be converted to JSONArray
Changed this to get the JSONObject:
JSONObject lJSONObject = new JSONObject(JsonR);
for (int i = 0; i < lJSONObject.length(); i++)
{
clientsArray.add(Integer.valueOf(lJSONObject.getString("ID")), lJSONObject.getString("Name"));
}
In PHP:
$jsonArray = array();
while($Row = $Rows->fetch_array(MYSQLI_ASSOC)) {
$RowsArray = array("ID" => $Row['ID'], "Name" => $Row['Name']);
array_push ($jsonArray, $RowsArray);
}
echo json_encode($jsonArray);
Now I get the error:
org.json.JSONException: Value [{"ID":"1","Name":"Client 1"},{"ID":"2","Name":"Client 2"},{"ID":"3","Name":"Client 3"}] of type org.json.JSONArray cannot be converted to JSONObject
It is not a JSONObject now? Why it say it is a JSONArray?

Because this is a JSON Object
{"1":"Client 1","2":"Client 2","3":"Client 3"}
JSON Array should be like this
[{"1":"Client 1","2":"Client 2","3":"Client 3"}]
This is an example for you but this is a wrong JSON Array.
Whats wrong? How to fix?
You are trying to convert JSON objects to JSON Array. And also another problem. Your JSON Object does not contain these objects ID and Name. Need to fix it like this {"clients":[{"id":1,"name":"Client 1"},{"id":2,"name":"Client 2"},{"id":3,"name":"Client 3"}]}

Related

serialize a json using gson

I am using com.google.gson.JsonObject to send the json inside 'parameters' to a rest endpoint.
{
"parameters":
"{
\"customer\" : {
\"firstName\": \"Temp\",
\"lastName\": \"Temp\",
\"emailAddresses\": [\"temp1#temp.com\"],
\"address\": {
\"street1\": \"123 W Temp St\",
\"city\": \"Temp\",
\"state\": \"Illinois\",
\"zipCode\": \"61122\"
}
},
\"options\" : [\"tv\"]
}"
}
Since Parameters is a json string, I am trying to do this :
JsonObject json = new JsonObject();
json.addProperty("options", ??);
I am not sure how to do it for customer and options.
'options' is a java Set, whereas customer is an object.
You may use:
Gson gson = new Gson();
String json = "{\"parameters\": {\"customer\" ... ";
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
JsonArray options = new JsonArray();
options.add("tv");
jsonObject.add("options", options);
String output = gson.toJson(jsonObject);

Extract JSONObject and iterate through HashMap field

I am trying to iterate through a value (that is a hashMap) of a JSONObject.
First I get a server response that is a String.
Then I turn it into a String! like this:
val responseString = response.serverResponse
Then I turn it into a JSONObject like this:
val jsonObj = JSONObject(responseString.toString()).get("data")
I do the second step because I only want to keep the LinkedHashMap shown in the picture attached.
But the second step returns type "Any" and then I cant iterate through the LinkedHashMap
JSONObject myjsonObject = new JSONObject();
Iterator keyvalues = jsonObject.keys();
while(keys.hasNext()) {String key = keyvalues.next();
if (myjsonObject.get(key) instanceof myjsonObject) {
}
}

JSP, Simple JSON - Parsing each key in the dictionary

I have a JSON dictionary as follows:
JSONObject jsonColMap = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
I want to loop this in JSP such that I can do a for each key in this dictionary, do something. I tried to do the following but I run into an error:
aWF = (JSONObject) jsonParser.parse(request.getParameter("data"));
Set<String> entries = jsonColMap.entrySet();
Iterator<String> iter = entries.iterator();
while(iter.hasNext())
{
String key = iter.next().toString();
if(aWF.containsKey(key))
{
//do something
}
}
But this throws an error
java.util.HashMap$EntrySet cannot be cast to java.util.HashMap
What am I doing wrong ?
EDIT: It complains at the line where entries is created and assigned

How to obtain unescaped string value of Newtonsoft.Json deserialized value?

I am trying to parse some JSON objects which is made just of (string,string) pairs. The file I am parsing contains this. I want ot emulate resjson behaviour.
{
"first_key": "first_value",
"unicode": "\u0040 #"
}
What I do is
string path = #"d:\resjson\example.resjson";
string jsonText = File.ReadAllText(path);
IDictionary<string, string> dict;
try
{
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonText);
}
catch(Exception ex)
{
// log or something
}
When I obtain the dict object, the
foreach (var pair in _dict)
{
string key = pair.Key;
string value = pair.Value;
Console.WriteLine("Key = '{0}', Value = '{1}'", key, value);
}
This inputs for me :
"Key = 'first_key', Value = 'first_value'"
"Key = 'unicode', Value = '# #'"
Once Newtonsoft.Json deserializes the object, I lose the "\u0040" string and I have no way of knowing how the original file looked like. Is there a way to preserve character escaping ?
Well, one simple idea would be to escape all the backslashes in the original text before passing it to the parser:
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(
jsonText.Replace(#"\", #"\\"));
Using Newtonsoft.Json, you can actually do:
var settings = new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
var json = JsonConvert.SerializeObject([obj or JToken], settings);
It won't show the original string as that is lost when deserializing, but it will encode all non ascii characters as \uXXXX

how to convert an object from json format to integer format

I am passing an array from view to the controller using json.stringify() method.
That value is passed to the controller and is in
"\"[{\\\"id\\\":1 "id\\\":2}]\"" format. I think this is in json format, I want to convert this into {id:1,id:2} format.
I tried to convert this into string format using JsonConvert.SerializeObject(),
but it is displaying in "\"\\\"[{\\\\\\\"id\\\\\\\":1}]\\\"\"" format.
Can you tell me how can I convert into {id:1,id:2} format/integer format?
The JSON data represents an array containing a dictionary as far as I can tell. You could get hold of a Dictionary representation of the data like this:
var json = "[{\"id\":1, \"id\": 2}]";
Dictionary<string, int>[] obj = JsonConvert.DeserializeObject<Dictionary<string, int>[]> (json);
var dict = obj[0];
I'm not sure if this is what you're after though, since you're saying that you want to display it like {id: 2}. If you want to print it out like that, you can build a string representation of the Dictionary:
var sb = new StringBuilder();
sb.Append("{");
foreach (var item in dict)
{
sb.Append(string.Format("{0}: {1}, ", item.Key, item.Value));
}
sb.Remove(sb.Length - 2, 2);
sb.Append("}");
Console.WriteLine(sb.ToString());
This prints {id: 2}.
To retrieve the value for 'id', if this is what you mean, you can do this:
var val = dict["id"];
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<object[]>(jsonString);