Convert LitJson.JsonData to Json String

Hello guys,
I use LitJson I have an object in JsonData that I want to get the string json, this object is not a class, for example not a person class, and a variable object that can contain different fields and values every time.

Ex:
{“JsonText”: {“matchId”: 166, “status”: 1, “userId”: 27, “IdItype”: 6}

or
{“JavaText”: {“caracId”: 25, “statusHelp”: 2503, “userId”: 27, “myValue”: 6, “values”: [{“id”: 1, “value”: “response” , {“Id”: 2, “value”: “read”}]}}

And other options …

I wear

JsonData data = JsonMapper.ToObject (json_text);

However there are parts that I want to get from the data object and transform into json string, for example field values above.

This example below does not work:

String s = null;
If (data [“values”]. IsObject)
S = JsonMapper.ToJson (data [“values”]); // error
Else
S = data [“values”]. ToString ();

How to convert JsonData (data [“values”]) into Json String?

thank you all

I don’t understand. What is your JsonData coming from? I use json.net and some coworkers use unitys json, but usually there is a to/from json when you want to convert.

Neither of those pieces of your data will validate as json. Are you sure you’re showing the correct data?
Usually with json, you’re converting into a class from a string or from a class variable holding data into a string. There are other tools like simple json and ways you can access just single fields, but I’m not sure if that is what you are looking for.

2 Likes

Using Json .Net you can use JObject.Parse on your json string. So let’s say you want just the “Values” property of the first example.

var jo = JObject.Parse(jsonString);

var valuesJson = jo["JsonText"]["values"].ToString();

And that’s it… JObject is like a Dictionary / Associative Array. It lets you traverse the tree (even use xpath like syntax if you’d like) and then call .ToString() which will output the Json string. You could also do ToObject() if you wanted to deserialize it to a specific class, but in your case you said there isn’t one.

Perfect I bought the Json .NET package and it worked perfectly, with LitJson not working the way I needed to work.

Thank you all for your help

1 Like

You’re very welcome. :slight_smile: