Compare JSON array and JSON object: Cannot convert Array to String error

convert json array to java list of objects
json array to json object
convert jsonarray to arraylist java 8
convert json array to java list of objects jackson
how to get json object from json array in java
jsonarray to list java 8
convert json string to arraylist java
json string array to list java

I am trying to compare json value and based on that i want to update the existing value,for example, currently we have "value" : [r0] in json, i want to compare and if value : [r0] ,then update it to [r0,r1] but iam hiting error that it cannot compare and there is a cast issue, could someone suggest what could be done

public void updateJsonParameter(string file)    
{
    try
    {

        var list = new List<string> { "joe", "test" };
        JArray array = new JArray(list);
        var jobject = JObject.Parse(file);
        var ringvalue = (string)jobject["properties"]["parameters"]["ringValue"]["value"];   // unable to case here and compare  
        jobject["properties"]["parameters"]["ringValue"]["value"] = array;          // able to update value but i want to update after comparing the existing values 
        var result = JsonConvert.SerializeObject(jobject);
    }

following is the json format

{
  "properties": {
    "displayName": "jayatestdefid",
    "description": "test assignment through API",
    "metadata": {
      "assignedBy": "xyz@gmail.com"
    },
    "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MGTest/providers/Microsoft.Authorization/policyDefinitions/test",
    "parameters": {
      "ringValue": {
        "value": ["r0"]
      }
    },
    "enforcementMode": "DoNotEnforce",
    }
}

First, as Klaycon said in his answer, it's worth noting that your "value" is not a single string. In json, whenever you see [ and ] then you have a collection, or an array, or a list.

When I work with json strings, I always like to be able to convert them into a strongly typed object. There is a very handy online tool I use all the time: http://json2csharp.com/

I took your json string that you provided and pasted it into that website. Here is that your object(s) look like when converted into c# classes:

public class RootObject // You can name this whatever you want
{
    public Properties properties { get; set; }
}

public class Metadata
{
    public string assignedBy { get; set; }
}

public class RingValue
{
    public List<string> value { get; set; }
}

public class Parameters
{
    public RingValue ringValue { get; set; }
}

public class Properties
{
    public string displayName { get; set; }
    public string description { get; set; }
    public Metadata metadata { get; set; }
    public string policyDefinitionId { get; set; }
    public Parameters parameters { get; set; }
    public string enforcementMode { get; set; }
}

Now, we can easily do the logic you need as follows:

// This is your json string, escaped and turned into a single string:
string file = "{  \"properties\": {    \"displayName\": \"jayatestdefid\",    \"description\": \"test assignment through API\",    \"metadata\": {      \"assignedBy\": \"xyz@gmail.com\"    },    \"policyDefinitionId\": \"/providers/Microsoft.Management/managementgroups/MGTest/providers/Microsoft.Authorization/policyDefinitions/test\",    \"parameters\": {      \"ringValue\": {        \"value\": [\"r0\"]      }    },    \"enforcementMode\": \"DoNotEnforce\",    }}";

// Convert your json string into an instance of the RootObject class
RootObject jobject = JsonConvert.DeserializeObject<RootObject>(file);

// Get a list of all the "values"
List<string> values = jobject.properties.parameters.ringValue.value;

// Loop over your colleciton of "value" and do your logic
for (int i = 0; i < values.Count; ++i)
{
    if (values[i] == "r0")
    {
        values[i] = "r0,r1";
    }
}

// And finally, turn your object back into a json string
var result = JsonConvert.SerializeObject(jobject);

And this is the final result:

{ 
   "properties":{ 
      "displayName":"jayatestdefid",
      "description":"test assignment through API",
      "metadata":{ 
         "assignedBy":"xyz@gmail.com"
      },
      "policyDefinitionId":"/providers/Microsoft.Management/managementgroups/MGTest/providers/Microsoft.Authorization/policyDefinitions/test",
      "parameters":{ 
         "ringValue":{ 
            "value":[ 
               "r0,r1"
            ]
         }
      },
      "enforcementMode":"DoNotEnforce"
   }
}

Converting JSONarray to ArrayList, ArrayList<String> listdata = new ArrayList<String>(); JSONArray jArray = ( JSONArray)jsonObject; if (jArray != null) { for (int i=0;i<jArray.length();i++){� JSON.Stringify() and toString()¶ The JSON.stringify() method converts an object or value to a JSON string. JSON.stringify skips some JavaScript-specific objects, such as properties storing undefined, symbolic properties, and function properties. The toString( ) method is called without arguments and should return a string. The string you


jobject.properties.parameters.ringValue.value is an array ["r0"] with one element "r0". If you want to check if it's an array with one element and that element is "r0", do exactly that:

var ringvalue = jobject["properties"]["parameters"]["ringValue"]["value"];
if(ringvalue.length == 1 && ringvalue[0] == "r0")
  jobject["properties"]["parameters"]["ringValue"]["value"] = array;

org.json.JSONArray.getJSONObject java code examples, getJSONArray("posts"); for (int i = 0; i < arr.length(); i++) { String post_id = arr. JSONArray array; for(int n = 0; n < array.length(); n++) { JSONObject object = array. e) { // This is here so that when the user rips the last page they don't get a "end_cursor not a string" error try { return json. Convert string to JSON array. JSON Values. In JSON, values must be one of the following data types: a string; a number; an object (JSON object) an array; a boolean; null; In JavaScript values can be all of the above, plus any other valid JavaScript expression, including: a function; a date; undefined; In JSON, string values must be written with double quotes:


You could compare the ringvalue (which is an JArray) using JArray.DeepEquals and then replace if the comparison returns true. For example,

var list = new List<string> { "joe", "test" };
JArray array = new JArray(list);
JArray valueToCompare = new JArray(new[]{"r0"});

var ringvalue = (JArray)jobject["properties"]["parameters"]["ringValue"]["value"];  

if(JArray.DeepEquals(ringvalue,valueToCompare))
{   
   jobject["properties"]["parameters"]["ringValue"]["value"] = array;         
}

org.json.JSONArray java code examples, public String creatingJsonString() { JSONArray pets = new JSONArray(); pets.put( "cat"); Example for different access methods in JSON object. public void readLine()) != null) { jsonScan.append(line); reader.close(); } catch (IOException e) { LOGGER.error(e. Which Collection should I convert in JSON and parse again? Dismiss Join GitHub today. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.


How to Convert JSON array to String array in Java , This tutorial is similar to our last article in JSON about How to convert JSON object to Java object, instead of JSON object, here we will convert� array and object - When merging an array with an object, the object is autowrapped as an array and then the rule above is applied. So [ 1, 2 ] merged with { "a" : true } is [ 1, 2, { "a": true } ]. objects - When merging two objects, the two objects are concatenated into a single, larger object.


JSONArray, public class JSONArray extends java.lang.Object. A JSONArray is an ordered The values can be any of these types: Boolean , JSONArray , JSONObject , Number , String , or the JSONObject. Returns: null if there is a syntax error. value for the index, or if the value is not a number and cannot be converted to a number. So, I did what I wanted to do which is iterating over the JSON object converted to an Array and convert it back to JSON. Code : // Converts a string to TitleCase function toTitleCase(str) { return str.replace(/\w\S*/g, function (txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } /** * @jsonArray :


jsonTuples: JSON Parser and Comparator in Java, Once the JSON parser was done, I tried to find a way to compare two JSON texts to counterparts cannot be split further, and while JSONObject and JSONArray JSONArray.parse(String valueString) : expect the valueString is only API used to convert Java Objects to JSON values defined in jsonTuples,� Start by looking at what the json contains. This may help: json2csharp - generate c# classes from json[] - it generates C# clases from a JSON string that you can then use (or compare with) the classes in your app.