0

What's the C# solution to decode a json string into string array, without knowing the class variables? It must be compatible with .Net 3.5 or .Net4.0, as I have to support older version of Unity.

below is my json return from a web request. There is no guarantee if their json format will change in the future or not. Thus, json object array, or dictionary style would solve my concern.

{"items":[{
    "price":"10.00",
    "downloaded":"Yes",
    "date":"2022-01-01",
    "quantity":"1",
    "reason":null,
    "other_license":"No",
    "package":"packageName",
    "currency":"EUR",
    "refunded":"No",
    "invoice":"IN0123456789",
    "MoreItem1":"value",
    "MoreItem2":"value",
    "MoreItem3":"value"
}]}

I found this method from other post, but it cause error of "Unexpected node type".

private struct JsonArrayWrapper<T>
{
    public T wrap_result;
}

public static T ParseJsonArray<T>(string json)
{
    var temp = JsonUtility.FromJson<JsonArrayWrapper<T>>("{\"wrap_result\":" + json + "}");
    return temp.wrap_result;
}

//below lines cause error
string[] options = ParseJsonArray<string[]>(json);
for (int i = 0; i < options.Length; i++)
{
    Debug.Log(options[i]);
}

Any suggestion will be very much appreciated.

thelghome
  • 225
  • 1
  • 9
  • 1
    well currently there is no root level array but rather you have everything nested in an object with a field `items` ... You are basically doing `"{"wrap_result": {"items":[{"price":"10.00","downloaded":"Yes",...."}]} }` which is not even close to the correct structure for a `string[]` ... – derHugo Mar 18 '22 at 11:49
  • `There is no guarantee if their json format will change in the future or not.` Well what use is deserializing the JSON if you won't be able to use anything of it because you don't know if the field names etc change? At a certain point you will have to go with a fix code structure and if he API ever changed adopt to the changes ... – derHugo Mar 18 '22 at 11:50
  • What's the best way if I want to parse this part? {"price":"10.00", "downloaded":"Yes",...} like a dictionary style, of searching price for the return value of "10.00". – thelghome Mar 18 '22 at 12:02

0 Answers0