converting list in json response to comma delimed - json

Hi I have below json response object converted to string
json object:
{"docInformation":[{"docsWithinTheAlertingRegion":[2134,12521],"toatlNotifiedViaSms":0,"totalAccepted":1}]}
How to convert the docsWithinTheAlertingRegion":[2134,12521] to comma delimited text docsWithinTheAlertingRegion":2134,12521?
The output I want is json object:
{"docInformation":[{"docsWithinTheAlertingRegion":2134,12521,"toatlNotifiedViaSms":0,"totalAccepted":1}]}
Below is snippet of my code
**BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
System.out.println("line number:"+ inputLine);
response.append(inputLine);
}
in.close();
JSONObject jsonObj = new JSONObject(response.toString());
String str = XML.toString(jsonObj);**

i dont understand what your code do
But This Pure JS code do what u need
data={"docInformation":[{"docsWithinTheAlertingRegion":[2134,12521],"toatlNotifiedViaSms":0,"totalAccepted":1}]}
data.docInformation.forEach(function (info , index){
var tmresult =""
info.docsWithinTheAlertingRegion.forEach(function (x){
tmresult += "," + x.toString()
})
data.docInformation[index].docsWithinTheAlertingRegion =tmresult.substring(1)
})
print(data)

Related

A JSONArray text must start with '[' at 1 [character 2 line 1] : Need Help Parsing Json

I've been trying to parse this but am getting the error : Exception in thread "main" java.util.concurrent.CompletionException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
System.out.println("Which city would you like to find the weather for?");
try (Scanner s = new Scanner(System.in)) {
city = s.nextLine();
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=26aa1d90a24c98fad4beaac70ddbf274")).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse :: body)
//.thenAccept(System.out::println)
.thenApply(Main::parse)
.join();
}
public static String parse(String responseBody) {
JSONArray weather = new JSONArray(responseBody);
for (int i = 0; i < weather.length(); i++) {
JSONObject weatherObj = weather.getJSONObject(i);
int id = weatherObj.getInt("id");
// int userID = weatherObj.getInt("userId");
// String title = weatherObj.getString("title");
System.out.println(id + " "/* + title + " " + userID*/);
}
return null;
}
since your url returns an object, not array, try
JSONObject weather = new JSONObject(responseBody);
The API you are calling doesn't return an array but an object, so you have to deserialze to an object and not to an array. The data you are after is probably the weather property of that response object.
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray weather = jsonResponse.getJSONArray("weather");

JSON Object Exception

I am writing a web service-REST.
I am receiving a text_plain format.
Example of my data:
{"data_log":
{
"methodClass": [{"methodName": 1, "methodStatus": "1"},
{"methodName": 2, "methodStatus": "1"}]
}
}
In my Restful Webservice, I try to read the data, but I got error 500 Internal Server Error-JSON Object not found.
public int adaptiveAuth(String objDataLog){
logWriter("objDataLog:"+objDataLog);
JSONObject obj = new JSONObject(objDataLog);
JSONArray methodClassObj=(JSONArray)obj.get("methodClass");
if (methodClassObj != null) {
JSONObject methodObj;
String entrymethodName, entrymethodStatus;
for (Object o : methodClassObj) {
methodObj = (JSONObject) o;
entrymethodName = String.valueOf(methodObj.get("methodName"));
entrymethodStatus = String.valueOf(methodObj.get("methodStatus"));
logWriter("entrymethodName:"+entrymethodName);
logWriter("entrymethodStatus:"+entrymethodStatus);
}
}
}
I already tried to use the below code, but it still give me the error.
String methodClass= obj.getJSONObject("data_log").getString("methodClass");
I'm expecting to put the current data into an 2 dimension array which it would be like this:
[1,1],[2,1]
Anyone could give me some suggestion on how to solve this issue?
**Try this code for parsing json data**
ArrayList<HashMap<String, String>> list;
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray b= jsonObj.getJSONArray("methodClass");
// looping through All data
for (int i = 0; i < b.length(); i++) {
JSONObject c = b.getJSONObject(i);
String entrymethodName = c.getJSONObject("methodClass").getString("methodName");
String entrymethodStatus = c.getJSONObject("methodClass").getString("methodStatus");
// tmp hash map for storing values
HashMap<String, String> co = new HashMap<>();
// adding each child node to HashMap key => value
co.put(entrymethodName, entrymethodStatus );
// adding co to list
list.add(co);
Also check this - https://gist.github.com/codebutler/2339666
I changed by String to this format:
{ "methodSet": [
{
"methodName": 1,
"methodStatus": "1"
},
{
"methodName": 2,
"methodStatus": "1"
}
]
}
and for the code :
ArrayList<String> listMethod = new ArrayList<String>();
JSONArray arr=(JSONArray)obj.get("methodClass");
if (arr != null) {
JSONObject objMethod;
String MethodName, MethodStatus;
for (Object o : arr) {
objMethod = (JSONObject) o;
MethodName = String.valueOf(objMethod.get("methodName"));
MethodStatus = String.valueOf(objMethod.get("methodStatus"));
int resultMethodName = Integer.parseInt(MethodName);
int resultMethodStatus = Integer.parseInt(MethodStatus);
logWriter("MethodStatus"+resultMethodName);
logWriter("MethodName"+resultMethodStatus);
listMethod.add("(" + MethodName + "," + MethodStatus + ")");
logWriter("listMethod is : "+listMethod);
}
}

How to get data from json one by one?

I have json datatype
{"email":"mikekhlau#gmail.com","contact":[{"contact_name":"Mike Lau","contact_no":"019-3331976"},{"contact_name":"Jason Lau","contact_no":"013-2711188"},{"contact_name":"Margaret Lau","contact_no":"019-3122281"}]}
How can I get email, contact_name and contact_no?
var json = {"email":"mikekhlau#gmail.com","contact":[{"contact_name":"Mike Lau","contact_no":"019-3331976"},{"contact_name":"Jason Lau","contact_no":"013-2711188"},{"contact_name":"Margaret Lau","contact_no":"019-3122281"}]}
You can get data by..
json.email
"mikekhlau#gmail.com"
json.contact[0].contact_name
"Mike Lau"
json.contact[0].contact_no
"019-3331976"
try {
JSONObject jsonRootObject = new JSONObject(strJson);
String email = jsonRootObject .getString("email");
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("contacts");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_name = jsonObject.getString("contact_name");
String contact_no= jsonObject.getString("contact_no");
}
} catch (JSONException e) {e.printStackTrace();}
}
use the above code

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

json parsing in blackberry?

I am working on a web-service application using JSON.
In performing task I got success in directly fetching JSOn response by hitting the URL.
Now I have a task to request with a request parameter.
enter code here
private void callJSON_Webservice(String method,String paraLastModifiedDate) {
HttpConnection c=null;
InputStream is = null;
String feedURL = Constants.feedURL;
int rc;
try{
JSONObject postObject = new JSONObject();
postObject.put("CheckLatestDataDate",method);
postObject.put("LastModifiedDate", paraLastModifiedDate);
//c = new HttpConnectionFactory().getHttpConnection(feedURL);
c = (HttpConnection)Connector.open(feedURL + ConnectionManager.getConnectionString());
// Set the request method and headers
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
c.setRequestProperty("Content-Length", "" + (postObject.toString().length() - 2));
//c.setRequestProperty("method", HttpConnection.GET);
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();
String json = StringUtils.convertStreamToString(is);
object = new JSONObject(json);
}catch (Exception e) {
System.out.println(e+"call webservice exception");
}
}
With this code I am getting EOF exception. I need to complete this small task as soon as possible. Please help me...!
Thanx in advance
Try replacing
is = c.openInputStream();
String json = StringUtils.convertStreamToString(is);
with following:
is = c.openInputStream();
StringBuffer buffer = new StringBuffer();
int ch = 0;
while (ch != -1) {
ch = is.read();
buffer.append((char) ch);
}
String json = buffer.toString();
Reference: convert StreamConnection to String