JSON Array conversion to CSV - json

I want to convert JSON to CSV. I am using the list function to meet the purpose.
But I am not getting desirable output for JSON array. Please find the sample JSON and list function which I am using:
Sample JSON document:
{
"NAME": "Viv",
"EMAIL": "lo",
"PUBLIC_OFFICIALS_CONTACTED": [{
"NAME_PUBLIC_OFFICIAL": [ "ff"],
"TITLE_PUBLIC_OFFICIAL": ["ff"]
}]
,
"COMMUNICATION_TYPE": ["Meeting","Phone","Handout","Conference"],
"NAMES_OF_OTHERS_FROM_XXX": [{
"NAME_OF_OTHERS": ["ff"],
"TITLE_OF_OTHERS": [ "ff"]
}]
,
"COMMUNICATION_BENEFIT": "Yes",
"AFFILIATE_NAME": "name",
"COMMUNICATION_ARRANGED": "Yes, arranged by you"
}
and list function which I am using is:
function(head, req) {
var row,
first = true;
// output HTTP headers
start({
headers: {
'Content-Type': 'text/csv'
}
,
});
// iterate through the result set
while(row = getRow()) {
// get the doc (include_docs=true)
var doc = row.doc;
// if this is the first row
if (first) {
// output column headers
send(Object.keys(doc).join(',') + 'n');
first = false;
}
// build up a line of output
var line = '';
// iterate through each row
for(var i in doc) {
// comma separator
if (line.length > 0) {
line += ',';
}
// output the value, ensuring values that themselves
// contain commas are enclosed in double quotes
var val = doc[i];
if (typeof val == 'string' && val.indexOf(',') > -1) {
line += '"' + val.replace(/"/g,'""') + '"';
}
else {
line += val;
}
}
line += 'n';
// send the line
send(line);
}
};
Please find attached the CSV output and expected output exported in excel.
Also, there is an issue in saving checkbox values. Please help me in writing the list function for the above JSON conversion to CSV.
current output:
expected output:

CSV is a single, flat list of values in each row, and one row of headers. The expected output shared in this question isn't compatible with CSV - it will be necessary to "flatten" your JSON by unpacking the nested data structures and making them instead into a flat hierarchy of data that can then become CSV. Try searching for "JSON to CSV" with a search engine for some examples - hope that helps!

I have refered this gitHUb link and tried the following:
JsonFlattener.class : Which will read the json string & extract the key & value
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonFlattener {
public Map<String, String> parse(JSONObject jsonObject) throws JSONException {
Map<String, String> flatJson = new HashMap<String, String>();
flatten(jsonObject, flatJson, "");
return flatJson;
}
public List<Map<String, String>> parse(JSONArray jsonArray) throws JSONException {
List<Map<String, String>> flatJson = new ArrayList<Map<String, String>>();
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, String> stringMap = parse(jsonObject);
flatJson.add(stringMap);
}
return flatJson;
}
public List<Map<String, String>> parseJson(String json) throws Exception {
List<Map<String, String>> flatJson = null;
try {
JSONObject jsonObject = new JSONObject(json);
flatJson = new ArrayList<Map<String, String>>();
flatJson.add(parse(jsonObject));
} catch (JSONException je) {
flatJson = handleAsArray(json);
}
return flatJson;
}
private List<Map<String, String>> handleAsArray(String json) throws Exception {
List<Map<String, String>> flatJson = null;
try {
JSONArray jsonArray = new JSONArray(json);
flatJson = parse(jsonArray);
} catch (Exception e) {
throw new Exception("Json might be malformed");
}
return flatJson;
}
private void flatten(JSONArray obj, Map<String, String> flatJson, String prefix) throws JSONException {
int length = obj.length();
for (int i = 0; i < length; i++) {
if (obj.get(i).getClass() == JSONArray.class) {
JSONArray jsonArray = (JSONArray) obj.get(i);
if (jsonArray.length() < 1) continue;
flatten(jsonArray, flatJson, prefix + i);
} else if (obj.get(i).getClass() == JSONObject.class) {
JSONObject jsonObject = (JSONObject) obj.get(i);
flatten(jsonObject, flatJson, prefix + (i + 1));
} else {
String value = obj.getString(i);
if (value != null)
flatJson.put(prefix + (i + 1), value);
}
}
}
private void flatten(JSONObject obj, Map<String, String> flatJson, String prefix) throws JSONException {
Iterator iterator = obj.keys();
while (iterator.hasNext()) {
String key = iterator.next().toString();
if (obj.get(key).getClass() == JSONObject.class) {
JSONObject jsonObject = (JSONObject) obj.get(key);
flatten(jsonObject, flatJson, prefix);
} else if (obj.get(key).getClass() == JSONArray.class) {
JSONArray jsonArray = (JSONArray) obj.get(key);
if (jsonArray.length() < 1) continue;
flatten(jsonArray, flatJson, key);
} else {
String value = obj.getString(key);
if (value != null && !value.equals("null"))
flatJson.put(prefix + key, value);
}
}
}
}
CSVWriter.class:Which transform the json string to CSV file
import org.apache.commons.lang.StringUtils;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class CSVWriter {
public void writeAsCSV(List<Map<String, String>> flatJson, String fileName) throws FileNotFoundException {
Set<String> headers = collectHeaders(flatJson);
String output = StringUtils.join(headers.toArray(), ",") + "\n";
for (Map<String, String> map : flatJson) {
output = output + getCommaSeperatedRow(headers, map) + "\n";
}
writeToFile(output, fileName);
}
private void writeToFile(String output, String fileName) throws FileNotFoundException {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fileName));
writer.write(output);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(writer);
}
}
private void close(BufferedWriter writer) {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCommaSeperatedRow(Set<String> headers, Map<String, String> map) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replace(",", "");
items.add(value);
}
return StringUtils.join(items.toArray(), ",");
}
private Set<String> collectHeaders(List<Map<String, String>> flatJson) {
Set<String> headers = new TreeSet<String>();
for (Map<String, String> map : flatJson) {
headers.addAll(map.keySet());
}
return headers;
}
}
JSONtoCSV.class : which will use the above class to parse the json & write the key values as a .csv file
import java.util.List;
import java.util.Map;
public class JSONtoCSV {
public static void main(String[] args) throws Exception {
String jsonString = "{\n" +
"\"NAME\": \"Viv\",\n" +
"\"EMAIL\": \"lo\",\n" +
"\n" +
"\"PUBLIC_OFFICIALS_CONTACTED\": [{\"NAME_PUBLIC_OFFICIAL\": [ \"ff\"],\n" +
"\"TITLE_PUBLIC_OFFICIAL\": [\"ff\"]}],\n" +
"\n" +
"\"COMMUNICATION_TYPE\": [\"Meeting\",\"Phone\",\"Handout\",\"Conference\"],\n" +
"\n" +
"\"NAMES_OF_OTHERS_FROM_XXX\": [{\"NAME_OF_OTHERS\": [\"ff\"],\n" +
"\"TITLE_OF_OTHERS\": [ \"ff\"]}],\n" +
"\n" +
"\"COMMUNICATION_BENEFIT\": \"Yes\",\n" +
"\"AFFILIATE_NAME\": \"name\",\n" +
"\"COMMUNICATION_ARRANGED\": \"Yes, arranged by you\"\n" +
"}";
JsonFlattener parser = new JsonFlattener();
CSVWriter writer = new CSVWriter();
List<Map<String, String>> flatJson = parser.parseJson(jsonString);
writer.writeAsCSV(flatJson, "C:/sample.csv");
}
}

Related

parsing Json in Android Studio when result is empty

I try to load datas from a Json that is on my server to my smartphone.
When the json is like this, it works and i get the label "spanishguitar":
{"file": "image.jpg", "objects": [{"bbox": [611, 82, 1231, 1265], "label": "spanishguitar", "prob": 0.991}]}
Here is my code:
public void updateLabel() {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
instrumentname = jsonResult.objects.get(0).label;
But sometimes the json is empty like this:
{"file": "image.jpg", "objects": []}
So my plan is that if objects == null to get something like:
Toast.makeText(getApplicationContext(), "Uuuups, itś empty", Toast.LENGTH_SHORT).show();
Do you know how to parse the json, so that i get a message in the case of an empty "objects"?
Thank you!
Now it works. Here is my code:
#RequiresApi(api = Build.VERSION_CODES.N)
private void empty() throws IOException {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(String.valueOf(json));
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if (objects == null || objects.size() == 0) {
/////////////
runOnUiThread(new Runnable() {
#Override
public void run() {
noResult.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Identification failed", Toast.LENGTH_SHORT).show();
}});
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
} else {
updateLabel();
}
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
Thank you a lot for your help!
'Empty' is not 'null'.You can use
ArrayUtils.isEmpty(objects)
or
objects == null || objects.length() == 0
to detect whether you got an empty objects.
I writed a demo for you:
import com.google.gson.*;
public class Main
{
public static void main(String[] args)
{
JsonParser parser = new JsonParser();
// JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": []}");
JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": [{\"bbox\": [611, 82, 1231, 1265], \"label\": \"spanishguitar\", \"prob\": 0.991}]}");
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if(objects == null || objects.size() == 0) {
System.out.println("objects is empty");
}else{
JsonObject firstObj = objects.get(0).getAsJsonObject();
System.out.println("objects[0].label="+firstObj.get("label"));
}
}
}

Read arbitrarily json data to a javafx treeview,and only show the first element of any array in it

I need to show a json file on a javafx treeview,the structure of the json is unknown.Like the web site: json viewer site
I show the tree for user to select path of a value(like xpath of xml),so if the json is too big,I only need to show the first element of any array in json.
for example,the original data is:
{
name:"tom",
schools:[
{
name:"school1",
tags:["maths","english"]
},
{
name:"school2",
tags:["english","biological"]
},
]
}
I want to show:
again:the structure of json is unknown,it is just one example.
There's no other option than recursively handling the json and create the TreeItem structure based on the element info.
(There's probably a better way of adding the symbols, but I didn't find appropriate icons.)
private static final String INPUT = "{\n"
+ " name:\"tom\",\n"
+ " schools:[\n"
+ " {\n"
+ " name:\"school1\",\n"
+ " tags:[\"maths\",\"english\"]\n"
+ " },\n"
+ " {\n"
+ " name:\"school2\",\n"
+ " tags:[\"english\",\"biological\"]\n"
+ " },\n"
+ " ]\n"
+ "}";
private static final Image JSON_IMAGE = new Image("https://i.stack.imgur.com/1slrh.png");
private static void prependString(TreeItem<Value> item, String string) {
String val = item.getValue().text;
item.getValue().text = (val == null
? string
: string + " : " + val);
}
private enum Type {
OBJECT(new Rectangle2D(45, 52, 16, 18)),
ARRAY(new Rectangle2D(61, 88, 16, 18)),
PROPERTY(new Rectangle2D(31, 13, 16, 18));
private final Rectangle2D viewport;
private Type(Rectangle2D viewport) {
this.viewport = viewport;
}
}
private static final class Value {
private String text;
private final Type type;
public Value(Type type) {
this.type = type;
}
public Value(String text, Type type) {
this.text = text;
this.type = type;
}
}
private static TreeItem<Value> createTree(JsonElement element) {
if (element.isJsonNull()) {
return new TreeItem<>(new Value("null", Type.PROPERTY));
} else if (element.isJsonPrimitive()) {
JsonPrimitive primitive = element.getAsJsonPrimitive();
return new TreeItem<>(new Value(primitive.isString()
? '"' + primitive.getAsString() + '"'
: primitive.getAsString(), Type.PROPERTY));
} else if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
TreeItem<Value> item = new TreeItem<>(new Value(Type.ARRAY));
// for (int i = 0, max = Math.min(1, array.size()); i < max; i++) {
for (int i = 0, max = array.size(); i < max; i++) {
TreeItem<Value> child = createTree(array.get(i));
prependString(child, Integer.toString(i));
item.getChildren().add(child);
}
return item;
} else {
JsonObject object = element.getAsJsonObject();
TreeItem<Value> item = new TreeItem<>(new Value(Type.OBJECT));
for (Map.Entry<String, JsonElement> property : object.entrySet()) {
TreeItem<Value> child = createTree(property.getValue());
prependString(child, property.getKey());
item.getChildren().add(child);
}
return item;
}
}
#Override
public void start(Stage primaryStage) {
JsonParser parser = new JsonParser();
JsonElement root = parser.parse(INPUT);
TreeItem<Value> treeRoot = createTree(root);
TreeView<Value> treeView = new TreeView<>(treeRoot);
treeView.setCellFactory(tv -> new TreeCell<Value>() {
private final ImageView imageView;
{
imageView = new ImageView(JSON_IMAGE);
imageView.setFitHeight(18);
imageView.setFitWidth(16);
imageView.setPreserveRatio(true);
setGraphic(imageView);
}
#Override
protected void updateItem(Value item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
imageView.setVisible(false);
} else {
setText(item.text);
imageView.setVisible(true);
imageView.setViewport(item.type.viewport);
}
}
});
final Scene scene = new Scene(treeView);
primaryStage.setScene(scene);
primaryStage.show();
}

How to parse JSON and urlencoded responses with Jetty HttpClient?

Please recommend the optimal approach for parsing urlencoded or JSON-encoded responses when using Jetty HttpClient.
For example, I have created the following utility class for sending ADM-messages and use BufferingResponseListener there, with UrlEncoded.decodeUtf8To​ (for parsing bearer token response) and JSON.parse (for parsing message sending response):
private final HttpClient mHttpClient;
private final String mTokenRequest;
private String mAccessToken;
private long mExpiresIn;
public Adm(HttpClient httpClient) {
mHttpClient = httpClient;
MultiMap<String> params = new MultiMap<>();
params.add("grant_type", "client_credentials");
params.add("scope", "messaging:push");
params.add("client_id", "amzn1.application-oa2-client.XXXXX");
params.add("client_secret", "XXXXX");
mTokenRequest = UrlEncoded.encode(params, null, false);
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
if (result.getResponse().getStatus() % 100 == 4) {
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
Map<String, String> resp = (Map<String, String>) JSON.parse(jsonStr);
String reason = resp.get("reason");
if ("AccessTokenExpired".equals(reason)) {
postToken();
} else if ("Unregistered".equals(reason)) {
// delete the invalid ADM registration id from the database
}
}
return;
}
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
Map<String, String> resp = (Map<String, String>) JSON.parse(jsonStr);
String oldRegistrationId = (String) result.getRequest().getAttributes().get("registrationID");
String newRegistrationId = resp.get("registrationID");
if (newRegistrationId != null && !newRegistrationId.equals(oldRegistrationId)) {
// update the changed ADM registration id in the database
}
}
};
private final BufferingResponseListener mTokenListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (result.isSucceeded()) {
String urlencodedStr = getContentAsString(StandardCharsets.UTF_8);
MultiMap<String> params = new MultiMap<>();
UrlEncoded.decodeUtf8To(urlencodedStr, params);
long now = System.currentTimeMillis() / 1000;
mExpiresIn = now + Long.parseLong(params.getString("expires_in"));
mAccessToken = params.getString("access_token");
}
}
};
public void postMessage(String registrationId, int uid, String jsonStr) {
long now = System.currentTimeMillis() / 1000;
if (mAccessToken == null || mAccessToken.length() < 32 || mExpiresIn < now) {
postToken();
return;
}
mHttpClient.POST(String.format("https://api.amazon.com/messaging/registrations/%1$s/messages", registrationId))
.header(HttpHeader.ACCEPT, "application/json")
.header(HttpHeader.CONTENT_TYPE, "application/json")
.header(HttpHeader.AUTHORIZATION, "Bearer " + mAccessToken)
.header("X-Amzn-Type-Version", "com.amazon.device.messaging.ADMMessage#1.0")
.header("X-Amzn-Accept-Type", "com.amazon.device.messaging.ADMSendResult#1.0")
.attribute("registrationID", registrationId)
.content(new StringContentProvider(jsonStr))
.send(mMessageListener);
}
private void postToken() {
mHttpClient.POST("https://api.amazon.com/auth/O2/token")
.header(HttpHeader.ACCEPT, "application/json")
.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded")
.content(new StringContentProvider(mTokenRequest))
.send(mTokenListener);
}
The above class works okay, but seeing that there are Jetty-methods with InputStream in arguments, like
UrlEncoded.decodeTo​(java.io.InputStream in, MultiMap map, java.lang.String charset, int maxLength, int maxKeys)
and
JSON.parse​(java.io.InputStream in)
I wonder if there is a smarter way to fetch and parse... maybe with something more effective than BufferingResponseListener?
In other words my question is please:
How to use the "streaming" version of the above parsing methods with HttpClient?

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

Json parsing Using Volley does not get cahced

I Parse json using volley framework, which every time gets response from the server, does not check the cache, It has taken a whole day, Here is my code. Any of you have used volley for parsing json are expected to help
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(diag_url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
// handle data, like converting it to xml, json, bitmap etc.,
// Parsing json
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
try {
DiagRegPojo test = new DiagRegPojo();
JSONObject obj = jsonArray.getJSONObject(i);
String testName = obj.getString("content");
Log.d("Response From Cache", testName);
test.setTitle(testName);
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
// Creating volley request obj
JsonArrayRequest testReq = new JsonArrayRequest(diag_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DiagRegPojo test = new DiagRegPojo();
test.setTitle(obj.getString("content"));
Log.d("Response From Server", obj.getString("content"));
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
})
{
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Set-Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Content-Type", "application/x-www-form-urlencoded");
//headers.put("Content-Type","application/json");
headers.put("Accept", "application/x-www-form-urlencoded");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(testReq);
}
}
To cache images, I have used this. sure it can be of some help to you.
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
.
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}