0

In Xamarin.Forms project I have JSON file saved as Embedded Resource. I get it as FileStream by calling:

var assembly = typeof(App).GetTypeInfo().Assembly;

FileStream fileStream = assembly.GetFiles()[0];

How do I parse this stream to json string? I know it is most likely super dumb question but I am confused, all I achieved was some random characters.

RealFinn
  • 13
  • 2
  • 5
  • 1. Read the entire stream into a string. 2. Deserialize string into json using library of your choice. – Pranav Hosangadi May 19 '21 at 17:52
  • See https://learn.microsoft.com/en/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#how-to-read-json-as-net-objects-deserialize where Microsoft describes how to deserialize JSON. Also see https://stackoverflow.com/a/3314213/7565574 how to read embedded resources. I think GetFiles() would return the assembly itself. – ckuri May 19 '21 at 18:13
  • If you have a `Stream` and you want to get the text the stream represents, create a `StreamReader` using the stream and read the text using the `StreamReader` (e.g. `ReadToEnd()`, `ReadLine()`, etc.). See duplicate. – Peter Duniho May 19 '21 at 18:18

1 Answers1

1

First, get the raw string from the JSON file by using

string jsonText = File.ReadAllText("/path/to/file.txt")

From there, you can convert the JSON string into an object (if needed):

MyClass jsonObj = JsonSerializer.Deserialize<MyClass>(jsonText);

Don't forget to import System.Text.Json.Serialization, System.Text.Json, and System.IO when working with JSON files.

You're having errors because you're trying to get a literal FileStream, which is not the intended use for it. You can read more about serializing JSONs here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0

Jeff Chen
  • 600
  • 5
  • 13
  • What is JsonUtility? Is it from Unity? For new .NET code System.Text.Json is recommended by MS. – ckuri May 19 '21 at 18:19
  • Sorry you're right, JsonUtility is from Unity, fixing it now – Jeff Chen May 19 '21 at 18:22
  • So basically I did the same thing that @JeffChen posted. What I discovered is the problem is loading the file, not my reading it. Thanks for help – RealFinn May 19 '21 at 18:34