Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
Answer from Victor Dodon on Stack OverflowInstead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
There is an answer of your question: https://stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
You should convert your list to a JSON Array, and just use its toString() function:
JSONArray myArray = new JSONArray(jsonObjlist);
// ...
String arrayToJson = myArray.toString(2);
The int parameter specifies the indent factor to use for formatting.
You can also direct use
String jsonString = new ObjectMapper().writeValueAsString(jsonObjectList)
To get the desired ouptput
Here is the small example
List<JSONObject> jsons = new ArrayList<>();
jsons.add(new JSONObject(ImmutableMap.of("Attribute", "EmailAddress", "Value", "[email protected]")));
jsons.add(new JSONObject(ImmutableMap.of("Attribute1", "EmailAddress3", "Value1", "[email protected]")));
System.out.println(new ObjectMapper().writeValueAsString(jsons));
The output is
[{"Value":"[email protected]","Attribute":"EmailAddress"},{"Attribute1":"EmailAddress3","Value1":"[email protected]"}]
I suspect there are some toString() method in any object that you have override?
You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
For any one who looks for answer yet:
1.Add jackson-databind library to your build tools like Gradle or Maven
2.in your Code:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
You can use json2csharp.com to Convert your json to object model
- Go to json2csharp.com
- Past your JSON in the Box.
- Clik on Generate.
- You will get C# Code for your object model
- Deserialize by
var model = JsonConvert.DeserializeObject<RootObject>(json);using NewtonJson
Here, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
public static class Helper
{
public static string AsJsonList<T>(List<T> tt)
{
return new JavaScriptSerializer().Serialize(tt);
}
public static string AsJson<T>(T t)
{
return new JavaScriptSerializer().Serialize(t);
}
public static List<T> AsObjectList<T>(string tt)
{
return new JavaScriptSerializer().Deserialize<List<T>>(tt);
}
public static T AsObject<T>(string t)
{
return new JavaScriptSerializer().Deserialize<T>(t);
}
}
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
How about this ?? Sorry to my bad format... first writting..
Public void convert(Object jsonData){
Wrapper convertedData = (Wrapper)JSON.deserialize(JSON.serialize(jsonData),Wrapper.Class);
String objectName = convertedData.getObjectName();
(do something....)
}
Class Wrapper{
String objectName;
String fieldName;
( some else...)
String getObjectName(){
return objectName;
}
}
As long as your string is valid JSON, you can use your Wrapper class, which follows data model of the JSON, and deserialize into it. Simply use JSON.deserialize(<your_json_string>, <wrapper_class>.class); from JSON Class.
String originalValues = '[{"FieldName":"AccountId","FieldType":"lookup-Account","ObjectName":"Opportunity","Operator":"=","Value":"0016E00000TIZUYQA5"}]';
List<WrapperLine> wrapperLines = (List<WrapperLine>)JSON.deserialize(value, List<WrapperLine>.class);
The original "list" is not well-formed JSON. Perhaps you meant the following:
[{"a":1, "b":2}, {"c":3, "d":4}, {"e":5, "f":6}]
If it is in a file called testFile.json, you can import it as JSON:
jsonLst = Import[FileNameJoin[{"path", "to", "testFile.json"}], "JSON"];
If the snippet is a string called str, you can import it as follows:
jsonLst = ImportString[str, "JSON"];
In either case, you will have a list of lists of rules:
(* jsonLst = {{"a" -> 1, "b" -> 2}, {"c" -> 3, "d" -> 4}, {"e" -> 5, "f" -> 6}} *)
You can now convert this into the structure you desire. One of the several ways to do it is the following:
res = jsonLst // Nest[Map, Apply[List], 2];
(* {{{"a", 1}, {"b", 2}}, {{"c", 3}, {"d", 4}}, {{"e", 5}, {"f", 6}}} *)
EDIT
Following the suggestion by Mr. Wizard, this is indeed more general:
res = jsonLst // ReplaceAll[Rule -> List]
My intention was to actually give a more restricted solution so as to avoid unintended side-effects.
EDIT 2
And following the suggestion by b3m2a1, here is his recommended solution:
res = jsonLst // Replace[#, Rule -> List, {3}, Heads -> True] &
If you like, you can call the JSONTools on the string directly:
json = "[{\"a\":1, \"b\":2}, {\"c\":3, \"d\":4}, {\"e\":5, \"f\":6}]";
JSONTools`FromJSON[json]
(* {
{"a" -> 1, "b" -> 2},
{"c" -> 3, "d" -> 4},
{"e" -> 5, "f" -> 6}
} *)
you can get this data as a JsonArray
You can customize a little bit of code like it
public static void main(String[] args) throws ParseException {
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(
data);
JSONArray jasonArray = json.getJSONArray("data");
List list = new ArrayList();
int size = jasonArray.length();
int i = 0;
while (i < size) {
list.add(jasonArray.get(i));
i++;
}
System.out.println(list);
}
There is a built-in method to convert a JSONObject to a String. Why don't you use that:
JSONObject json = new JSONObject();
json.toString();
You can use:
JSONObject jsonObject = new JSONObject();
jsonObject.toString();
And if you want to get a specific value, you can use:
jsonObject.getString("msg");
or Integer value
jsonObject.getInt("codeNum");
For long Integers
jsonObject.getLong("longNum");