JSONArray cannot be converted to JSONObject in Asynctask - json

I am trying to Parse JSON Data get From URL and Insert Data to Firebase from response using asynctask.Below is the code I have written but it is not inserting any data to Firebase.My Firebase Reference is correct as I log.e Below is the code
JSONArray arr = new JSONArray(result);
mDatabase = FirebaseDatabase.getInstance().getReference().child(context.getResources().getText(R.string.bid_request).toString().trim()).child("b");
for(int i=0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
Map<String, Object> userValues = new HashMap<>();
final String node = obj.getString("mysql_id");
final String id = obj.getString("id");
DatabaseReference newBid = mDatabase.child(node);
String data = obj.getString("new_comer");
String[] items = data.split(",");
for (String item : items) {
userValues.put(item, 1);
}
serValues.put("tReq", obj.getString("tReq"));
newBid.setValue(userValues, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.e("error", "onComplete: "+databaseError);
}
}
});
And below is the Error showing in my log.Can not figure out what is wrong I am doing
E/myapp: onPostExecute: org.json.JSONException: Value [{"id":"14248","mysql_id":"a6555018-de41-4fc7-942e-530389aa3a9d","tReq":"4","new_comer":"10019,10029"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject

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

Increasing maxjsonlength on MVC post from Javascript

I have a controller action Export which accepts a List of models like below. This is sending back and manipulated dataset back from the view where the user could interact with it. So we have been able to send the data down with much more information.
[HttpPost]
public JsonResult Export(List<MappingExportModel> sources){}
This works fine in all cases but there is one where we have a bigger than normal dataset. This is causing an issue with the export. So far I have tried just passing the values as an object or string but I am unable to convert them into any usable instance after the data is into the controller.
Is it possible to preemptively increase this maxjsonlength value somewhere. The value from the web.config is being ignored from what I have come across so far.
The error I receive is
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property"
I need to be able to accept this directly from the ajax request into the controller action. Spinning up a version of JsonResult and then setting the max value will not work because the error is thrown the the data is trying to be deserialized into the object var presented above. We get the value in the original GET request and do set the value before the view is loaded. Now we are taking the data from this view and sending it back plus all the manipulations the users have created.
User posts data to server, the controller action is hit with the data. The error is encountered and spit back out to the browser which handles the error.
You can use custom json length. add the following file in your project and edit your global.asax.cs
Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
///// **********
JsonValueProviderFactory jsonValueProviderFactory = null;
foreach (var factory in ValueProviderFactories.Factories)
{
if (factory is JsonValueProviderFactory)
{
jsonValueProviderFactory = factory as JsonValueProviderFactory;
}
}
//remove the default JsonVAlueProviderFactory
if (jsonValueProviderFactory != null) ValueProviderFactories.Factories.Remove(jsonValueProviderFactory);
//add the custom one
ValueProviderFactories.Factories.Add(new CustomJsonValueProviderFactory());
/////*************
}
}
///******** for json length
public sealed class CustomJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength. This could be read in from the web.config if you prefer
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object jsonData = GetDeserializedObject(controllerContext);
if (jsonData == null)
{
return null;
}
Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
AddToBackingStore(backingStore, String.Empty, jsonData);
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
JsonValueProviderFactory.cs
public sealed class JsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength. This could be read in from the web.config if you prefer
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object jsonData = GetDeserializedObject(controllerContext);
if (jsonData == null)
{
return null;
}
Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
AddToBackingStore(backingStore, String.Empty, jsonData);
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
by this you can pass lengthy json through ajax to controller and if you want to retrieve a lengthy string back to ajax result from controller then add below code in your controller also
//add this for getting large json string
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}

Java save json byte array image to particular location

I have one application that posts json data like below
{
"image": "data:image/png;base64,eAvQPaQEJCABCUjg/wNeEta73J3yXwAAAABJRU5ErkJggg==................"
}
It posts image(png or jpg) base64 byte array in the "image" key.
I want to save that image under the name "datetime.png" into my specified location.
For this I am using the code below:
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/getImage")
public Response GetImage(String json) {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
String currentTime = sdf.format(dt);
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
String imageCode=innerJsonObj.getString("image");
String base64Image = imageCode.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
FileOutputStream fos = new FileOutputStream("D:\\image\\" + currentTime + ".png");
try {
fos.write(imageBytes);
} finally {
fos.close();
}
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But it gives me the following Error
java.io.FileNotFoundException: D:\image\2016-07-15 17:04:34.png (The
filename, directory name, or volume label syntax is incorrect)

parse json for GWT SuggestBox

I want to parse a json response in Java and add its values to a suggestBox in GWT. It would be great if anyone can help me with a sample code.
["abc","def","ghi","jkl","mno","pqr","acb","dfe","gih","jlk","mon"]
public void parseResponse(String str){
MultiWordSuggestOracle oracle = new MultiWordSuggestOracle();
JSONValue jsonValue = JSONParser.parseLenient(str);
JSONArray jArray = jsonValue.isArray();
for(int i=0; i<jArray.size(); i++){
String companySymbol = jArray.get(i).isString().toString();
oracle.add(companySymbol);
}
}
You cannot use MultiWordSuggestOracle: you have to extend http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SuggestOracle.html
(and its callback)
ex:
class MySuggestOrc extends SuggestOracle {
public void requestSuggestions(final SuggestOracle.Request request, final SuggestOracle.Callback callback) {
Receiver<YourJsonContainer> receiver = new Receiver<YourJsonContainer>() {
#Override
public void onSuccess(YourJsonContainer companiesJsonHolder) {
List<Suggestion> companies = //... the code to split json
SuggestOracle.Response response = new SuggestOracle.Response();
response.setSuggestions(companies)
callback.onSuggestionsReady( request, response );
}
}
AsyncRequest req = // get you json respons here and use ...
}
}

MVC C# to Json correct way to format url in string array?

I'm trying to understand correct way to handle backslashes in urls within a string array that are returned via Json...I have commented the goal below
public JsonResult PhotosByListingId(int id)
{
var pics = _listingRepository.GetById(id).ListingPhoto.ToList();
List<string> l = new List<string>();
foreach(var p in pics)
{
//l.Add("albums\\/album1\\/" + p.PhotoName); //nope
//l.Add(#"albums\/album1\/" + p.PhotoName); //nope
l.Add("albums/album1/" + p.PhotoName); //????? nope
}
string[] s = l.ToArray();
return Json(s, JsonRequestBehavior.AllowGet);
//needs to be this..THE GOAL
// ["albums\/album1\/10k.jpg","albums\/album1\/10l.jpg","albums\/album1\/10y.jpg"]
//but is returning this?
// ["albums/album1/10k.jpg","albums/album1/10l.jpg","albums/album1/10y.jpg"]
}
You could try string.Replace:
public JsonResult PhotosByListingId(int id)
{
var pics = _listingRepository.GetById(id).ListingPhoto.ToList();
List<string> l = new List<string>();
foreach(var p in pics)
{
l.Add("albums/album1/".Replace("/", "\\/") + p.PhotoName);
}
string[] s = l.ToArray();
return Json(s, JsonRequestBehavior.AllowGet);
}
Because the javascript serialiser is converting the slashes, you could implement serialisation yourself and modify the generated JSON:
public string CustomSerialised()
{
string test = "/This/That/The other/";
List<string> arr = new List<string>();
arr.Add(test);
arr.Add(test);
arr.Add(test);
System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
return s.Serialize(arr).Replace("/","\\/");
}
This can be navigated to using the standard routing pattern when used within a controller.